我创建functionLibrary.swift
类来调用某些不同的ViewControllers中的某些函数。问题是当我执行应用程序时,println
中的ViewController.swift
函数首先工作,尽管它是在我从functionLibrary
调用的其他几行之后。
这是ViewController的logIn函数。 (funcLib是functionLibrary类型的值)
@IBAction func logIn(sender: AnyObject) {
var bodyData = ["op":"users","op2":"login","id":"","id2":"","id3":"","users_emailAddress":"asdasd@gmail.com","users_password":"asdasd"]
var requestData = funcLib.JSONStringify(bodyData) // This turns the data to string
var responseData = funcLib.HTTPPostRequest(requestData) // This is the http post request. Returns a bool and a Dictionary
println(responseData)
这是输出
(false, [:]) //responseData
response = <NSHTTPURLResponse: 0x7aad7290> { URL: http://asdasd.asdasd.com/services/index.php } { status code: 200, headers {
Connection = "keep-alive";
"Content-Length" = 57;
"Content-Type" = "application/json";
Date = "Sun, 26 Jul 2015 21:09:39 GMT";
Server = asdasd;
"X-Powered-By" = "PHP/5.4.43";
} }// The println in HTTPPostRequest
{
auth = *********;
"user_id" = ***;
} // The println in HTTPPostRequest
代码运行正常。没有运行时错误。但就像我说的那样首先执行println。如何在请求和响应之后执行它数据从funcLib函数获取数据?
谢谢。
答案 0 :(得分:1)
看起来funcLib.HTTPPostRequest
计划异步闭包并立即返回,而不等待HTTP响应。异步方法很好,但当然你不能期望在responseData
中找到从HTTP服务器返回的任何数据,当然logIn
中的println将立即执行,而HTTP的println响应将在以后发生,届时闭包将收到实际响应。
答案 1 :(得分:1)
我使用dispach_async()
方法解决了这个问题。
以下是新的HTTPPostRequest()
功能:
func HTTPPostRequest(link:String, bodyData: AnyObject, completion:((data: NSData?) -> Void)) {
println("HTTPPOST")
if let requestURL = NSURL(string: link){
let request = NSMutableURLRequest(URL: requestURL)
request.HTTPMethod = "POST"
let postString = JSONStringify(bodyData)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) in
completion(data: NSData(data: data))
if let error = error {
println("error:\(error)")
return
}
}.resume()
}
}
以下是如何调用HTTPPostRequest()
:
@IBAction func logIn(sender: AnyObject) {
var bodyData: AnyObject = ["op":"users","op2":"login","id":"","id2":"","id3":"","users_emailAddress":"asdasdasd","users_password":"asdasd"] as AnyObject
let response: () = funcLib.HTTPPostRequest("http://asdasd.asdasdasd.com/services/index.php", bodyData: bodyData){data in
dispatch_async(dispatch_get_main_queue()){
if let data = data {
let responseData = NSData(data: data)
let responseDic = NSJSONSerialization.JSONObjectWithData(data , options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println("\(responseDic)")
}
}
}
}
}