使用URLSession

时间:2016-06-24 07:32:07

标签: swift swift3

我正在使用URLSession从网址

中检索数据
func scheduleURLSession() {
    let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myIdentifier...")
    let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
    let retrieveTask = backgroundSession.downloadTask(with: URL(string: "https://api.wedsblog.net/v2/index.php?bitcoin&simple")!)
    retrieveTask.resume()
}

下载完成后

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { }

将被召唤。如何阅读下载文件的内容? “.downloadTask”是正确的功能还是我应该使用另一个?

2 个答案:

答案 0 :(得分:1)

找到以下解决方案:

已实施URLSessionDataDelegate

func scheduleURLSession() {
        let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: "myIdentifier")
        let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
        let retrieveTask = backgroundSession.dataTask(with: URL(string: "https://api.wedsblog.net/v2/index.php?bitcoin&simple")!)
        retrieveTask.resume()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    print(String(data: data, encoding: String.Encoding.utf8)!)
}

答案 1 :(得分:0)

let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) {(data, response, error) -> Void in { // First check if error is not nil
  // Second check what is status code of your http response
  // Third do with data what you want(parse to objects)
} 

我认为这很有帮助。