Why can't I append a String to a NSURL?

Frederick C. Lee picture Frederick C. Lee · Aug 18, 2014 · Viewed 13.3k times · Source

Appending the .txt file component to the URL path doesn't work:

var error:NSError?
let manager = NSFileManager.defaultManager()
let docURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error)
docURL.URLByAppendingPathComponent("/RicFile.txt") <-- doesn't work

via debugger:

file:///Users/Ric/Library/Developer/CoreSimulator/Devices/
<device id>/data/Containers/Data/Application/<app id>/Documents/

Writing a String using docURL to a file doesn't work because of the missing file name.

Reason (via error):

"The operation couldn’t be completed. Is a directory"

So Question: Why doesn't the following work?

docURL.URLByAppendingPathComponent("/RicFile.txt")

Answer

BergQuester picture BergQuester · Aug 18, 2014

URLByAppendingPathComponent: doesn't mutate the existing NSURL, it creates a new one. From the documentation:

URLByAppendingPathComponent: Returns a new URL made by appending a path component to the original URL.

You'll need to assign the return value of the method to something. For example:

let directoryURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error)
let docURL = directoryURL.URLByAppendingPathComponent("/RicFile.txt")

Even better would be to use NSURL(string:String, relativeTo:NSURL):

let docURL = NSURL(string:"RicFile.txt", relativeTo:directoryURL)