Swift URL 响应为零 [英] Swift URL Response is nil

查看:46
本文介绍了Swift URL 响应为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义的 DataManager 类.在它里面,我想在一个方法中获取数据并返回一个 NSData 对象,然后再转换为 JSON.

I have created a custom DataManager class. Inside it I want to fetch data in a method and return an NSData object to convert to JSON afterwards.

我尝试使用 completionHandler 获取数据,但没有成功:

I have tried to get the data using the completionHandler but no luck:

class func fetchData() -> NSData? {
    var session = NSURLSession.sharedSession(),
        result = NSData?()
    let DataURL : NSURL = NSURL(string: "http://...file.json")!

    let sessionTask = session.dataTaskWithURL(DataURL, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
        result = data
    })
    sessionTask.resume()
    return result
}

推荐答案

dataTask 异步运行.这意味着在您从 fetchData 返回时不会调用完成处理程序闭包.因此,result 尚未设置.

The dataTask runs asynchronously. That means that the completion handler closure will not be called by the time you return from fetchData. Thus, result will not have been set yet.

因此,您不应尝试从异步方法同步检索数据.相反,您应该自己使用异步完成处理程序模式:

Because of this, you should not try to retrieve data synchronously from an asynchronous method. Instead, you should employ an asynchronous completion handler pattern yourself:

class func fetchData(completion: @escaping (Data?, Error?) -> Void) {
    let session = URLSession.shared
    let url = URL(string: "http://...file.json")!

    let task = session.dataTask(with: url) { data, response, error in
        completion(data, error)
    }
    task.resume()
}

你会这样称呼它:

MyClass.fetchData { data, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // use `data` here; remember to dispatch UI and model updates to the main queue
}

// but do not try to use `data` here

...

仅供参考,有关 Swift 3 之前的原始语法,请参阅此答案的先前修订版.

FYI, for the original pre-Swift 3 syntax, see previous revision of this answer.

这篇关于Swift URL 响应为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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