2016-10-02 22 views
2

我發現這個真棒答案posting data to php爲郵政完成處理程序到服務器

唯一的問題是,我不知道如何將數據後恢復。

如何爲以下功能製作完成處理程序?

func postToServer(postURL: String, postString: String) { 
    let request = NSMutableURLRequest(URL: NSURL(string: postURL)!) 
    request.HTTPMethod = "POST" 
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ 
     data, response, error in 

     let responseString = String(data: data!, encoding: NSUTF8StringEncoding) 
     if responseString != nil { 
      print("responseString = \(responseString!)") 
     } 

    } 
    task.resume() 
} 

編輯:也許我沒有正確應用它,但建議的重複鏈接並沒有解決我的問題。請有人提供一個這樣的例子嗎?我一直堅持這樣的3周現在。我完全不知道如何從任務中提取數據。我已經閱讀了很多關於閉包的文章,但是我只是看不到它們在哪裏,甚至是如何相關。當我嘗試查找與任務相關的函數時,它只會給出響應...並且如果我在簡歷後沒有鍵入sleep(3),則返回nil。

我看過一堆視頻,其中人們擁有與我一樣的代碼,並且不使用完成處理程序並仍然獲取數據...什麼給了?

+0

的可能的複製[我怎麼能建立與斯威夫特完成處理程序的功能?(http://stackoverflow.com/questions/30401439/how-could- i-create-a-function-with-a-completion-handler-in-swift) –

+1

你正在調用一個異步方法,所以如果你想返回數據,你的函數還必須包含一個完成處理程序作爲參數。如果你想同步使用NSURL,那麼有一個擴展就是這麼做的。 http://stackoverflow.com/questions/26784315/can-i-somehow-do-a-synchronous-http-request-via-nsurlsession-in-swift – Sealos

+0

你能解釋一下你究竟在做什麼嗎? ?你想用'responseString'做什麼? –

回答

2

這個工作在迅速3

func postToServer(_ completion:@escaping ((_ response: String, _ success: Bool)-> Void), postURL: String, postString: String) { 
    let request = NSMutableURLRequest(url: NSURL(string: postURL)! as URL) 
    request.httpMethod = "POST" 
    request.httpBody = postString.data(using: String.Encoding.utf8) 

    let task = URLSession.shared.dataTask(with: request as URLRequest){ 
     data, response, error in 

     let responseString = String(data: data!, encoding: String.Encoding.utf8) 
     if responseString != nil { 
      print("responseString = \(responseString!)") 
      completion(responseString!, true) 

     } 

    } 
    task.resume() 
    } 
} 
+1

太棒了!謝謝你! –