Isha Balla
Isha Balla

Reputation: 763

How to save and fetch data from file in swift?

I want to save the response from JSON in a file and fetch from it when the network is not available. However on trying to fetch idea by disabling the wifi, the app always crashes. Are there any other ways for offline fetching in swift except saving in database??

This is the error I am getting : Could not cast value of type 'Swift._NSContiguousString' (0x109e22320) to 'NSArray'

This is what I have done so far:

Upvotes: 1

Views: 1011

Answers (1)

Wain
Wain

Reputation: 119041

I don't know that this is the only issue, but this code

class func loadSavedFile(fileName: String) -> AnyObject? {
    let pathString: String = Utility.fetchFilePathString(fileName)
    print("Here the pathString is \(pathString)")
    if NSFileManager.defaultManager().fileExistsAtPath(pathString) {
        return NSKeyedUnarchiver.unarchiveObjectWithFile(pathString)!
    } else {
        return "File doesn't exist"
    }
    return ""
}

Either returns an object or a string. That's not very sensible. It should return a success flag or a tuple or use a completion block. When you call this function your code expects to get back an array of directory, which in a number of cases won't happen

self.directorie = (Utility.loadSavedFile(Constants.File.kDirectory) as? [Directory])!

The error in your question indicates a different kind of data mismatch. You should try not to use AnyObject, let swift help you by type checking what you're doing...

Upvotes: 1

Related Questions