Search code examples
iosswiftwritetofile

Cannot writeToFile to NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true)


I'd like to save to file NSSearchPathForDirectoriesInDomains(.CachesDirectory,.UserDomainMask, true). I've written code as following, however it cannot save file on cachedirectory, its success becomes false. Could you tell me how to solve this problem? Thank you for your kindness.

    let paths2 = NSSearchPathForDirectoriesInDomains(
        .CachesDirectory,
        .UserDomainMask, true)
    let cachesPath: AnyObject = paths2[0]

    var user:NSDictionary = [
        "Name": "Tom",
        "Address": "Tokyo",
    ]

    let success = user.writeToFile(cachesPath as! String, atomically: true)

    if success {
        println("save sucess")
    }

Solution

  • Your trying to save a file with the path of the Caches directory. You can only write a file to a file path. To create a file path you append the name of the file to the directory you want to save it in like so:

    let paths2 = NSSearchPathForDirectoriesInDomains(
        .CachesDirectory,
        .UserDomainMask, true)
    let cachesPath: AnyObject = paths2[0]
    
    var user:NSDictionary = [
        "Name": "Tom",
        "Address": "Tokyo",
    ]
    
    let filePath = cachesPath.stringByAppendingPathComponent("CachedUser")
    let success = user.writeToFile(filePath, atomically: true)
    
    if success {
        println("save sucess")
    }