等待下载任务在NSURLSession中完成

编程入门 行业动态 更新时间:2024-10-07 06:41:06
本文介绍了等待下载任务在NSURLSession中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的情况如下所示:我有一个包含有一个函数的类,该函数向具有NSURLSession的服务器发出POST请求.我认为,在不在该类中的另一个函数中,我将该函数与其中的任务一起调用,该函数异步运行.我遇到以下问题:当我从服务器下载JSON响应并将其写入变量并返回时,我写入的变量仍然为零,因为它没有等待线程/任务完成下载并返回初始值nil.

My scenario looks like this: I have a class which has a function in it and this function makes a POST request to a server with NSURLSession. In another function which is not in that class I call that function with the task in it, which runs asynchronously I think. I'm encountering following problem: When I download the JSON response from the server and write it to a variable and return it, the variable I've written to is still nil since it didn't wait for the thread/task to finish downloading and returns the initial value which is nil.

所以我的问题是我如何才能等待该任务完成,然后继续执行整个程序.

So my question is how can I wait for that task to finish and then continue the whole program.

这是我的带有请求功能的课程:

This is my class with the request function:

class DownloadTask { var json:NSDictionary! var cookie:String! var responseString : NSString = "" func forData(completion: (NSString) -> ()) { var theJSONData:NSData! do { theJSONData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions()) } catch _ { print("error") } let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") if cookie != nil { request.setValue(cookie, forHTTPHeaderField: "Cookie") } request.HTTPBody = theJSONData let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print("error") return } else { completion(NSString(data: data!, encoding: NSUTF8StringEncoding)!) } } task.resume() }

}

这是我的通话代码:

let task = DownloadTask() task.forData { jsonString in do { if let json: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { if json["error"] != nil { authenticated = false } else { let result = json["result"] as! NSDictionary user.personId = result["personId"] as! NSNumber user.sessionId = result["sessionId"] as! NSString print("test0") authenticated = true } } } catch _ { print("error") } } print("test1")

输出为:

test1 test0

在执行此任务后,我无法访问变量user.sessionId.

And I can't acess the variables user.sessionId after that task.

推荐答案

正如我之前在主帖子的评论中所述,下载 NSURLSession.sharedSession().dataTaskWithRequest(request)可以同步运行主线程,这意味着它将数据同步下载到显示.简而言之, print("test0")将在分派的线程完成(也就是下载数据)后执行.为了解决这个问题,我不得不使用信号量(我还结合了原始问题的第一段代码和第二段代码):

As I said before in the comments of the main post the download NSURLSession.sharedSession().dataTaskWithRequest(request) run synchronously to the main thread which means it downloads the data synchronously to the displaying. So in short the print("test0") will be executed when the dispatched thread is finished (aka downloaded the data). To fix this I had to use semaphores (I also combined the first code and the second code from the original question):

private func downloadData(completion: (String) -> ()) { let semaphore = dispatch_semaphore_create(0); let request = NSMutableURLRequest(URL: url) var theJSONData = NSData() do { theJSONData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions()) } catch { completion(String()) } request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = theJSONData let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in data == nil ? completion(String()) : completion(String(data: data!, encoding: NSUTF8StringEncoding)!) dispatch_semaphore_signal(semaphore); } task.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); }

这可能不是最有效的解决方案,也不是最优雅的解决方案,但就我而言,我真的不得不等待下载完成,否则它什么也不会做.

This may not be the most efficient nor the most elegant solution but in my case I really had to wait for the downloading to be finished else it shouldn't do anything.

更多推荐

等待下载任务在NSURLSession中完成

本文发布于:2023-11-13 02:47:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSURLSession

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!