2016-03-18 63 views
1

我試着爲我的POST請求創建一個輔助類,並且想要返回響應。但是,由於發佈請求是異步的,這讓我感到有點困惑。使用輔助函數發送POST請求

我試過返回NSString,但它不讓我返回responseresponseString。它只是讓我把return "A"。我試圖使用-> NSURLResponse,但無法使其工作。

製作這種幫手方法的正確方法是什麼? (這也是好的,如果我做一個檢查後,我得到響應,並返回true或按虛假的響應)

class func hello(name: String) -> NSString { 

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!) 
    request.HTTPMethod = "POST" 
    let postString = "Hi, \(name)" 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
    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)") 

     } 

     let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding) 
     print("responseString = \(responseString)") 
    } 
    task.resume() 
    return "A" 
} 

回答

5

由於dataTaskWithRequest是異步的,則執行完成塊之前的功能會打你的return語句。你應該做的是爲你自己的幫助器方法設置一個完成塊,或者將某種委託對象傳遞給函數,以便你可以調用一個方法讓它知道web服務回調的結果是什麼。

下面是一個例子使用完畢塊:

class func hello(name: String, completion: (String? -> Void)){ 

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!) 
    request.HTTPMethod = "POST" 
    let postString = "Hi, \(name)" 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
    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)") 

     } 

     let responseString = String(data: data!, encoding: NSUTF8StringEncoding) 
     print("responseString = \(responseString)") 

     completion(responseString); 
    } 
    task.resume() 
} 

然後用它

<#YourClass#>.hello("name") { responseString in 

    //do something with responseString 
} 

還沒有測試的代碼,但應約權

+0

哇!王牌男人!謝謝!!! – senty

+1

注意行更改'let responseString = String(data:data !,編碼:NSUTF8StringEncoding)'將NSString更改爲String以更靈活 – Fonix

+1

還注意到我還沒有包含任何錯誤處理代碼,您自己如何處理 – Fonix