Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")
like image 783
Frederick C. Lee Avatar asked Aug 18 '14 00:08

Frederick C. Lee


1 Answers

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) 
like image 155
BergQuester Avatar answered Sep 22 '22 18:09

BergQuester