ZbadhabitZ
ZbadhabitZ

Reputation: 2913

NSURLSession - Garbage Data At End (WatchOS)

I'm hoping someone may be able to help me understand an issue I am facing when trying to implement a NSURLSession in my WatchOS 2 application.

For whatever reason, I receive the error;

Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end."
UserInfo={NSDebugDescription=Garbage at end.}

but only after I've run my app once. The first time I run the WatchOS app in the Simulator, the data I am downloading is received and parsed without issue. The second+ time I run the app, I receive the aforementioned error.

I have run my JSON through every possible validator I can find, and it validates with no problem. The data seems to work, but only on the first launch. If I watch a period of time (10+ minutes it seems), then run the app in the Simulator again, it works once, then I receive the error.

Here is my truncated code from the InterfaceController.swift file;

func getData() {

    let myURL = "http://www.myurl.com/sample.json"

    let dataURL = NSURL(string: myURL)

    let conf = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: conf)

    dataTask = session.dataTaskWithURL(dataURL!) { data, response, error in

    guard error == nil, let data = data else {
        return
        }

        do {

            let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSArray  

            for item in json {
                let name: String? = item["name"] as? String
                let email: String? = item["email"] as? String
                let nickName: String? = item["nickName"] as? String

                let file = Data(
                    name: name,
                    email: email,
                    nickName: nickName)

                self.files.append(file)

                dispatch_async(dispatch_get_main_queue()) {
                    self.reloadTable()
                }
            }

        } catch {
            print(error)
        }
    }
    dataTask!.resume()
}

Any thoughts would be greatly appreciated. Thank you!

Upvotes: 3

Views: 775

Answers (1)

zayaan
zayaan

Reputation: 56

Found a temporary fix. Set:

sessionConfig.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;

Looks like this is caused by a bug in the request cache.

Upvotes: 4

Related Questions