0

i am currently working with SpriteKit on Xcode 7 and ios 9 and i encountered that suggested URLByAppendingPathComponent method for accessing local urls for files with combination with archiveRootObject is not saving the object to the documents destination but in the Data folder. Here is the code

func saveData(){
   let objectToSave = SomeObject()

    let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let path = NSURL(string: docPath)
    let fp = path?.URLByAppendingPathComponent("savedObject.data")
    if NSKeyedArchiver.archiveRootObject(objectToSave, toFile: String(fp)) {
        print("Success writing to file!")
    } else {
        print("Unable to write to file!")
    }

}

This, however save the data but in the Data folder near the Bundle folder. (I havent tested it on a real device though).

In debugger the constant fp is holding correct NSURL string so i simply just dont get what am i doing wrong.

However, using let fp = docPath + "/savedObject.data"and subsequently in the archiveRootObject function saves the object in correct location although in debugger the strings are identical.

My question is, could someone please explain me, what is wrong with the first approach?

7
  • fp is an NSURL. Use the path method to get the URL as a file path.
    – rmaddy
    Sep 20, 2015 at 18:12
  • Thanks for reply. I know that fp is NSURL but isnt it convertible to string in String() method? Anyway, could you please be more specific how to achieve this? I am still little new to swift so understanding this would help me.
    – darksoul99
    Sep 20, 2015 at 18:29
  • 1
    Replace String(fp) with ftp.path. (I think that's right, I'm more an Objective-C person than Swift).
    – rmaddy
    Sep 20, 2015 at 18:31
  • Thanks a lot ! i just managed it myself too sec ago and that is really obvious from your first comment now :) thanks again. Anyway, you know why this is not working directly by String(fp) ? I am just curious when debugger shows correct url.
    – darksoul99
    Sep 20, 2015 at 18:36
  • Again, I don't know Swift well but I believe String(fp) tries to cast the NSURL into a String and it may do this using the description method. Print String(fp) and notice the output is not at all what you want.
    – rmaddy
    Sep 20, 2015 at 18:47

1 Answer 1

2

Nowadays, the best API to use for this is NSFileManager. You should also use NSURL path method instead of String(). I would recommend this:

if let docDir = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first,
    let filePath = docDir.URLByAppendingPathComponent("savedObject.data").filePathURL?.path
{
    // ...Write to the path
}

More on String(x):

I've copied the String initializer's definition below. You can see that it tries several different string representations and is mostly for debugging purposes — in the case of NSURL and many other NSObject subclasses, it calls the Obj-C description method. You should not rely on the result of description. Instead you should use whatever situation-specific methods are available, like path in this case.

extension String {
    /// Initialize `self` with the textual representation of `instance`.
    ///
    /// * If `T` conforms to `Streamable`, the result is obtained by
    ///   calling `instance.writeTo(s)` on an empty string s.
    /// * Otherwise, if `T` conforms to `CustomStringConvertible`, the
    ///   result is `instance`'s `description`
    /// * Otherwise, if `T` conforms to `CustomDebugStringConvertible`,
    ///   the result is `instance`'s `debugDescription`
    /// * Otherwise, an unspecified result is supplied automatically by
    ///   the Swift standard library.
    ///
    /// - SeeAlso: `String.init<T>(reflecting: T)`
    public init<T>(_ instance: T)
    ...
2
  • 1
    Thank you much for detailed explanation and suggestion on how to improve the code! With so many approaches its not often easy to decide which one is the best when books say one, internet says other and another approach is currently best....Its all about learning every time and i've got much to work on. Thanks again, cheers.
    – darksoul99
    Sep 20, 2015 at 21:29
  • Swift 3 syntax: if let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first ...
    – Olivier
    Nov 10, 2016 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.