Swift 2 数据库路径问题

Posted

技术标签:

【中文标题】Swift 2 数据库路径问题【英文标题】:Swift 2 Database Path Issues 【发布时间】:2015-12-22 23:09:43 【问题描述】:

我正在学习在 ios 应用程序开发期间使用数据库的文本教程 (http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_8_Application_using_Swift_and_FMDB)

在以下代码中:

     databasePath = docsDir.stringByAppendingPathComponent("contacts.db")

出现错误:

'stringByAppendingPathComponent' 不可用:在 NSURL 上使用 URLByAppendingPathComponent。

当我尝试这个建议时:

databasePath = NSURL(fileURLWithPath:NSTemporaryDirectory()).URLByAppendingPathComponent("contacts.db")

我意识到通过进行修改,我们现在使用的是 URL 而不是字符串,但我不知道要对代码进行哪些其他更改

完整代码:

import UIKit

类视图控制器:UIViewController

@IBOutlet weak var name: UITextField!
@IBOutlet weak var address: UITextField!
@IBOutlet weak var phone: UITextField!
@IBOutlet weak var status: UILabel!

var databasePath = NSString()

override func viewDidLoad() 
    super.viewDidLoad()

    let filemgr = NSFileManager.defaultManager()
    let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)

    let docsDir = dirPaths[0] as! String

    databasePath = docsDir.stringByAppendingPathComponent(
    "contacts.db")

    if !filemgr.fileExistsAtPath(databasePath as String) 

        let contactDB = FMDatabase(path: databasePath as String)

        if contactDB == nil 
            print("Error: \(contactDB.lastErrorMessage())")
        

        if contactDB.open() 
            let sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"
            if !contactDB.executeStatements(sql_stmt) 
                print("Error: \(contactDB.lastErrorMessage())")
            
            contactDB.close()
         else 
            print("Error: \(contactDB.lastErrorMessage())")
        
    


override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.


@IBAction func saveData(sender: AnyObject) 
    let contactDB = FMDatabase(path: databasePath as String)

    if contactDB.open() 

        let insertSQL = "INSERT INTO CONTACTS (name, address, phone) VALUES ('\(name.text)', '\(address.text)', '\(phone.text)')"

        let result = contactDB.executeUpdate(insertSQL,
            withArgumentsInArray: nil)

        if !result 
            status.text = "Failed to add contact"
            print("Error: \(contactDB.lastErrorMessage())")
         else 
            status.text = "Contact Added"
            name.text = ""
            address.text = ""
            phone.text = ""
        
     else 
        print("Error: \(contactDB.lastErrorMessage())")
    


@IBAction func findContact(sender: AnyObject) 
    let contactDB = FMDatabase(path: databasePath as String)

    if contactDB.open() 
        let querySQL = "SELECT address, phone FROM CONTACTS WHERE name = '\(name.text)'"

        let results:FMResultSet? = contactDB.executeQuery(querySQL,
            withArgumentsInArray: nil)

        if results?.next() == true 
            address.text = results?.stringForColumn("address")
            phone.text = results?.stringForColumn("phone")
            status.text = "Record Found"
         else 
            status.text = "Record not found"
            address.text = ""
            phone.text = ""
        
        contactDB.close()
     else 
        print("Error: \(contactDB.lastErrorMessage())")
    

【问题讨论】:

【参考方案1】:

URLByAppendingPathComponent 返回NSURL 是对的,但您始终可以使用absoluteString 将路径作为String 并继续使用该字符串,就像您已经做的那样:

let databaseURL = NSURL(fileURLWithPath:NSTemporaryDirectory()).URLByAppendingPathComponent("contacts.db")
let databasePath = databaseURL.absoluteString

或者你可以走捷径直接构建databasePath而不使用NSURL

let databasePath = NSTemporaryDirectory() + "database.db"

【讨论】:

以上是关于Swift 2 数据库路径问题的主要内容,如果未能解决你的问题,请参考以下文章

(Swift) UITableView - 尝试将索引路径移动到不存在的索引路径

来自 String 的 NSURL 被截断,UIVideoEditorController 的视频路径上的点 Swift 2 iOS 8

我无法在 swift 2.3 中播放保存在目录路径和 AVPlayer 中的视频

使用swift的临时文件路径

Swift XMLParser 检测元素结束

Xcode Swift - 在视图控制器之间传递按钮路径数据