swift를 사용하여 iOS 앱을 만들고 있습니다. 일부 GET 또는 POST HTTP 요청을 얻고 싶습니다. 나는 Alamofire가 존재하지만 내 자신의 기능을 만들고 싶다는 것을 알고 있습니다.IOS, Swift, NSURLSession의 기본 스레드에 액세스 할 수 없습니다.
은 내가 무슨 짓을 :
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
바로 전에 로그 할 수 있지만 dispatch_async(dispatch_get_main_queue(),block)
에 로그인하지 않습니다.
아이디어가 있으십니까?
정말 대단합니다. 고맙습니다. – soling