如何从 Swift NSURLSession 获取数据? [英] How to get data from a Swift NSURLSession?

查看:65
本文介绍了如何从 Swift NSURLSession 获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下代码:

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

我想将数据传输到类中的一个变量(类中的 str 变量).字符串 self.str = dann 不传达任何信息.我该怎么做?

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?

推荐答案

我不确定 NSString 是您想要的类型.JSON 可能是返回数据的格式,具体取决于您的 URL 的功能.我尝试了提供的代码并遇到了相同的问题,但如果您将其视为 JSON(我使用 httpbin.org 作为虚拟 URL 源)并且它有效.

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()

(感谢建议的编辑@sgthad.编辑与问题不是特别相关,但仍希望将代码更新为最新.)

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

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()

这篇关于如何从 Swift NSURLSession 获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆