'stringByAppendingPathComponent' is unavailable

情到浓时终转凉″ 提交于 2019-12-18 12:58:09

问题


I'm getting the error

'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead.

when I try to do

let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite")

This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5.

This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to NSString. But if I do convert it to an NSString

let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString)

then I get the error

'NSString' is not implicitly convertible to 'String'...

and it gives me the option to "fix-it" by inserting as String, which brings us back to the original error.

This also happens for stringByAppendingPathExtension.

What do I do?


回答1:


You can create a URL rather rather than a String path.

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileURL = documentsURL?.appendingPathComponent("test.sqlite")

If you absolutely need the path, then you can get it like this:

guard let path = fileURL?.path else {
    return
}

print(path) // path will exist at this point

There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths.

See also:

  • What's the difference between path and URL in iOS?
  • NSFileManager URL vs Path
  • Swift 2.0: Why Guard is Better than If



回答2:


You can use:

let dbPath = (documentsFolder as NSString).stringByAppendingPathComponent("db.sqlite")


来源:https://stackoverflow.com/questions/32120581/stringbyappendingpathcomponent-is-unavailable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!