C. Lewis
C. Lewis

Reputation: 145

How to Call HTTP Get and Save in Variable In Swift?

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.

Upvotes: 0

Views: 2651

Answers (1)

MwcsMac
MwcsMac

Reputation: 7168

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()

Upvotes: 2

Related Questions