Why can't I add a string to NSURL?

Adding the .txt component to the URL path does not 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 

through the 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 does not work due to a missing file name.

Reason (by mistake):

"The operation could not be completed. Is the directory"

So the question is: Why does the following not work?

 docURL.URLByAppendingPathComponent("/RicFile.txt") 
+6
source share
2 answers

URLByAppendingPathComponent: does not mutate an existing NSURL , it creates a new one. From the documentation :

URLByAppendingPathComponent: returns the new URL, the added path to the original URL.

You will need to assign the return value of the method to something. For instance:

 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) 
+19
source

With the Swift language update, the proposed call to manager.URLForDirectory (...) no longer works, because the call may cause (exception). Specific error: "The call may be thrown, but not marked" try ", and the error is not processed." The throw can be processed 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") } 
0
source

Source: https://habr.com/ru/post/973947/


All Articles