7

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")
Frederick C. Lee
  • 7,609
  • 13
  • 56
  • 89

2 Answers2

19

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) 
David Berry
  • 39,492
  • 12
  • 80
  • 91
BergQuester
  • 6,099
  • 24
  • 38
  • 1
    `NSURL(string:String, relativeTo:NSURL)` will also work. It is even arguably more correct if your appended URL string may not be a relative path. as it will correctly deal with the stringUrl being interpreted relative to the base url instead of just appending it. – David Berry Aug 18 '14 at 07:22
  • Hmm, I overlooked that one. I'll update the question, thanks! – BergQuester Aug 18 '14 at 14:50
  • You're actually changing the url to be absolute (starting it with /) where the original question seems to be relative. I've edited your answer to be more inline with that. – David Berry Aug 18 '14 at 21:28
0

With the update to the Swift language, the suggested call to manager.URLForDirectory(...) no longer works because the call can throw (an exception). The specific error is "Call can throw, but it is not marked with 'try' and the error is not handled". The throw can be handled with the following code:

    let directoryURL: NSURL?
    do
    {
        directoryURL = try manager.URLForDirectory(.DocumentationDirectory,
                            inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    }
    catch _
    {
        print("Error: call to manager.URLForDirectory(...) threw an exception")
    }
bennyty
  • 301
  • 4
  • 18
SwiftAero
  • 31
  • 3