0

My question is simple: how do you call a HTTP GET Request in Swift? I am trying to retrieve specific data from server (I have the URL string), the problem is that the previous answers I saw, doesn't explain thoroughly how to request an HTTP Get and save the retrieved information in a variable to be used later? Thanks in advance!

Here's what I have so far:

       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"

Not sure what do following requesting the GET.

C. Lewis
  • 145
  • 1
  • 6
  • 17
  • Possible duplicate of [How to make an HTTP request in Swift?](http://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift) – Nazmul Hasan Feb 24 '17 at 18:46
  • @NazmulHasan I actually looked at that response... but like I said in my question, it doesn't explain how to save the retrieved data from HTTP get into a variable. – C. Lewis Feb 24 '17 at 18:50
  • @C.Lewis " HTTP Get and save the retrieved information in a variable to be used later?" more detail .. you can do it several way – Nazmul Hasan Feb 24 '17 at 18:56

1 Answers1

2

In your post you are missing the part that does the actual getting to of the data.

Your code should look something like this to get the value out of the text file.

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()
MwcsMac
  • 6,810
  • 5
  • 32
  • 52