2016-06-12 30 views
-1

所以我有幾行將「登錄」到網頁,他們獲取內容並將其打印到控制檯,但我無法弄清楚如何從「任務」中獲得結果,並在代碼中稍後使用它們。在Swift中登錄後返回url的內容?

let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/mobilelogin.php")!) 
    request.HTTPMethod = "POST" 
    let username = email_input.text; 
    let password = password_input.text; 
    var postString = "username=" 
    postString += username! 
    postString += "&password=" 
    postString += password! 
    print(postString); 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
    print(request.HTTPBody); 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in guard error == nil && data != nil 
     else { 
      // check for fundamental networking error 
      print("error=\(error)") 
      return 
     } 

     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { 
      // check for http errors 
      print("statusCode should be 200, but is \(httpStatus.statusCode)") 
      print("response = \(response)") 
      return 
     } 

     let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)! 
     print("responseString = \(responseString)"); 
     return 

    } 
    print("This is the task string") 
    task.resume() 

回答

0

你不能從閉包返回,你需要使用「回調」。

我們爲你的代碼的函數:

func getData(username username: String, password: String) 

而不是添加返回類型,但是,我們添加一個回調,這裏命名爲「完成」:

func getData(username username: String, password: String, completion: (response: String)->()) { 

} 

而且裏面的功能,我們在數據可用的位置使用此回調:

func getData(username username: String, password: String, completion: (response: String)->()) { 
    let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/mobilelogin.php")!) 
    request.HTTPMethod = "POST" 
    var postString = "username=" 
    postString += username 
    postString += "&password=" 
    postString += password 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 
     guard let data = data where error == nil else { 
      fatalError(error!.debugDescription) 
     } 

     if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { 
      print("response = \(response)") 
      fatalError("statusCode should be 200, but is \(httpStatus.statusCode)") 
     } 

     guard let str = String(data: data, encoding: NSUTF8StringEncoding) else { 
      fatalError("impossible to get string from data") 
     } 

     completion(response: str) 

    } 
    task.resume() 
} 

而且您將使用它lik電子郵件:

getData(username: email_input.text!, password: password_input.text!) { (response) in 
    print(response) 
} 
+0

非常感謝! – inigomontoya333

+0

有沒有辦法讓我把它當成變量?用於標籤設置? – inigomontoya333

+0

不客氣。不要忘記[this](http://stackoverflow.com/help/someone-answers)。對於你的變量:當然! :)你做你想做的。在'getData'中,而不是'print(response)',只需要在需要時使用響應,標籤或其他任何東西。 – Moritz