'stringByAppendingPathComponent' is unavailable

前端 未结 2 1161
谎友^
谎友^ 2021-01-01 21:04

I\'m getting the error

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

when

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 21:26

    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

提交回复
热议问题