0

I get documents path by creat

func docPath() -> String {
  let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        return documentPaths[0]
}

Now, I would like to get a file path, that file is located under document path. I tried:

let documentPath = docPath()
let filePath = documentPath.stringByAppendingPathComponent("myFile")

But I get error: Value of type 'String' has no member 'stringByAppendingPathComponent'

Why?

Nishant Bhindi
  • 2,242
  • 8
  • 21
Leem
  • 17,220
  • 36
  • 109
  • 159

2 Answers2

2

Apple has removed the path manipulating API from String.

Two solutions:

  • Bridge cast String to NSString

    let filePath = (documentPath as NSString).appendingPathComponent("myFile")
    
  • Use the URL related API (recommended)

    func docURL() -> URL {
        return try! FileManager.default.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    }
    
    let documentURL = docURL()
    let fileURL = documentURL.appendingPathComponent("myFile")
    

The code is Swift 3+.

vadian
  • 274,689
  • 30
  • 353
  • 361
0

You have try this too. U have to convert to URL.

let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

let documentpath : URL =  URL(fileURLWithPath: documentPaths[0])
let filePath = documentpath.appendingPathComponent("myfile")
McDonal_11
  • 3,935
  • 6
  • 24
  • 55