【发布时间】:2015-02-03 19:17:34
【问题描述】:
我正在使用 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 函数的工作方式相同)。好吧,一切似乎都很好。我实现了2次使用这个GET函数,但第三次我想使用它,没有办法访问主线程发送数据。我可以在评论 //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) 中没有任何记录。
有什么想法吗?
【问题讨论】:
标签: ios swift grand-central-dispatch nsurlsession