[英]IOS, Swift, No way to access main thread in NSURLSession
我正在使用Swift創建一個iOS應用。 我想實現一些GET或POST HTTP請求。 我知道Alamofire存在,但我想創建自己的函數。
我做了什么 :
import Foundation
class DatabaseRequest:NSObject{
class func GET(urlAsString:String, completion : (response:NSURLResponse, result:AnyObject?, error:String?)-> Void){
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: configuration)
let url = NSURL(string: urlAsString)
let urlRequest = NSMutableURLRequest(URL: url!)
urlRequest.HTTPMethod = "GET"
session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
if let error = error{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: "GET Connection error : \(error.localizedDescription)")
})
}else{
var error:NSError?
let JSON_Object:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
if let error = error{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: "GET JSONSerialization error: \(error.localizedDescription)")
})
}else{
if let result:AnyObject = JSON_Object{
//The third time I use this class function, no way to access the main thred to send data
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: JSON_Object, error: nil)
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: nil)
})
}
}
}
session.finishTasksAndInvalidate()
}).resume()
}
class func POST(urlAsString:String, parameters:[String:AnyObject], completion:(response:NSURLResponse?, result:AnyObject?, error:String?)->Void){
println("POST used")
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session = NSURLSession(configuration: configuration)
var errorHTTPBody:NSError?
let url = NSURL(string: urlAsString)
let urlRequest = NSMutableURLRequest(URL: url!)
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &errorHTTPBody)
if let error = errorHTTPBody{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: nil, result: nil, error: "POST errorHTTPBody: \(error.localizedDescription)")
})
return
}
session.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
println(data)
if let error = error{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: "POST Connection error : \(error.localizedDescription)")
})
}else{
var error:NSError?
var JSON_Object:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error)
if let error = error{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: "POST JSONSerialization error : \(error.localizedDescription)")
})
}else{
if let result:AnyObject = JSON_Object{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: JSON_Object, error: nil)
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(response: response, result: nil, error: nil)
})
}
}
}
session.finishTasksAndInvalidate()
}).resume()
}
}
有趣的部分主要是GET函數(因為POST函數的作用相同)。 好吧,一切似乎都正常。 我實現了兩次使用此GET函數,但是第三次使用它,無法訪問主線程來發送數據。 我可以在評論之前//The third time I use this class function, no way to access the main thread to send data
之前記錄一些內容//The third time I use this class function, no way to access the main thread to send data
但是沒有任何日志記錄在dispatch_async(dispatch_get_main_queue(),block)
。
任何想法?
您在這里嘗試的操作對我來說有點奇怪。 您正在從主線程異步調度到主線程。 通常,您分派異步操作以在當前線程以外的另一個線程上並行執行某項操作,因此當前線程可以繼續執行其操作,而不必等待異步任務的完成。 當我與主線程無關時,調度到同一線程會使任務排隊等待稍后執行。 我不明白為什么要在主線程上執行這些任務。 只要您不嘗試操作UI對象,任何線程都可以。 我真的只會在觸摸UI時使用主線程。 現在開始執行HTTP提取或發布的問題,我建議遵循Apple傳播的方法。 那就是使用委托來處理異步回調。 蘋果已經定義了三種委托協議:NSURLSessionDelegate,NSURLSessionTaskDelegate,NSURLSessionDataDelegate。 我將創建一個類,例如實現以下協議的HTTPClient:
@interface HTTPClient : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSMutableDictionary *runningTasks;
- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data;
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error;
- (NSURLSessionTask *) startGetTaskForURL: (NSURL *) url;
@end
@implementation HTTPClient
- (NSURLSessionTask *) startGetTaskForURL: (NSURL *) url {
NSURLSessionTask *task = [self.session dataTaskWithURL:url];
NSMutableData *data = [NSMutableData data];
[task resume];
[self.runningTasks setObject:data forKey:task];
return task;
}
- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *) dataTask didReceiveData: (NSData *)data {
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSMutableData *runningData = [self.runningTasks objectForKey:task];
if (!runningData) {
NSLog(@"No data found for task");
}
[runningData appendData: data];
}
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSData *data = [self.runningTasks objectForKey:task];
//process the data received
}
@end
收到所有數據后,您可以執行必要的JSON處理。 當然,您需要初始化字典runningTasks。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.