How to get data from a Swift NSURLSession?

2020-07-26 16:47发布

问题:

For example, I have the following code:

let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        var dann = NSString(data: data, encoding: NSUTF8StringEncoding)!
        self.str = dann
})
task.resume()

I want to transfer the data to a variable in the class (the str variable in the class). The string "self.str = dann" does not convey anything. How can I do this?

回答1:

I'm not sure NSString is the type you want. JSON may be format of the data returned, depending on your URL's functionality. I tried the code provided and got the same issues, but if you treat it as JSON (I used httpbin.org as a dummy URL source) and it worked.

    let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://httpbin.org/get")!, completionHandler: { (data, response, error) -> Void in
        do{
            let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
            print(str)
        }
        catch {
            print("json error: \(error)")
        }
    })
    task.resume()

(thanks for suggested edit @sgthad. the edit is not particularly relevant to the question, but still wanted to update the code to be current.)

Update for Swift 3 syntax

let url = URL(string: "http://httpbin.org/get")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    guard let unwrappedData = data else { return }
    do {
        let str = try JSONSerialization.jsonObject(with: unwrappedData, options: .allowFragments)
        print(str)
    } catch {
        print("json error: \(error)")
    }
}
task.resume()


回答2:

Can you try dispatch_async?

let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
        dispatch_async(dispatch_get_main_queue(), {
           var dann = NSString(data: data, encoding: NSUTF8StringEncoding)!
           self.str = dann
        })
    }
    task.resume()


回答3:

// Swift 3 based for Quick ref.

let task = URLSession.shared.dataTask(with: NSURL(string: "http://httpbin.org/get")! as URL, completionHandler: { (data, response, error) -> Void in
    do{
       let str = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
       print(str)
    } catch {
        fatalError("json error: \(error)")
    }
})
task.resume()