2017-02-24 57 views
0

我的問題很簡單:如何在Swift中調用HTTP GET請求? 我想從服務器(我有URL字符串)檢索特定的數據,問題是,我看到的以前的答案,並沒有徹底解釋如何請求HTTP獲取並保存檢索到的信息在要使用的變量後來?提前致謝!如何調用HTTP獲取並保存在Swift中的變量?

這是我到目前爲止有:

 let myURL = NSURL(string:"https://api.thingspeak.com/channels/CHANNEL_ID/last_entry 
     _id.txt"); 

     let request = NSMutableURLRequest(url:myURL! as URL); 

     request.httpMethod = "GET" 

不知道什麼如下請求GET。

+0

你有什麼試過的?你想要檢索什麼類型的數據? XML還是JSON?顯示您嘗試過的代碼或有問題的代碼會讓您獲得更好的迴應。 – MwcsMac

+0

[如何在Swift中創建HTTP請求?]可能重複(http://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) –

+0

@MwcsMac我已更新我的問題在上面。 –

回答

0

在您的文章中,您缺少實際獲取數據的部分。

你的代碼應該看起來像這樣從文本文件中獲取值。

var lastID: String? 
let myURL = NSURL(string:"https://api.thingspeak.com/channels/1417/last_entry_id.txt"); 

let request = NSMutableURLRequest(url:myURL! as URL); 
//request.httpMethod = "GET" // This line is not need 
// Excute HTTP Request 
let task = URLSession.shared.dataTask(with: request as URLRequest) { 
    data, response, error in 

    // Check for error 
    if error != nil 
    { 
     print("error=\(error)") 
     return 
    } 

    // Print out response string 
    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
    print("responseString = \(responseString!)") 
    lastID = "\(responseString!)" // Sets some variable or text field. Not that its unwrapped because its an optional. 
} 

task.resume() 
+0

非常感謝你! –

+0

@ C.劉易斯沒有問題只是確保upvote和標記爲接受的答案。 – MwcsMac

相關問題