0
votes

I want to link my backend python with my front end ios swift app. I want to call for a get api call. I tried all the answers on stack overflow: like this one:

var url : String = "http://google.com?test=toto&test2=titi"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }

but it gave me an error on line 3 saying consecutive declarations on a line must be separated by ;

Also, I tried the following: override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 255/255.0,green:200/255.0,blue:100/255.0,alpha:1)

    let url = URL(string:"http://127.0.0.1:5000/")!

    let urlRequest = URLRequest(url: url)
    let session = URLSession.shared
    let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
       guard error == nil else {
         print("error calling GET on /todos/1")
         print(error!)
         return
       }// do stuff with response, data & error here
    })
    guard let responseData = data else{
        print("Error: did not receive data")
           return
    }

but data in line 11 was not identified

1
Instead of posting 2 different code samples I think you should focus on one and explain in more detail what the issue is with it. I strongly suggest you choose the second one since it is based on a more modern version of swift.Joakim Danielson
data should be inside of completionHandler block, not outside.erkutbas

1 Answers

1
votes

Looks like you're missing task.resume() in the second snippet (which should be the last line).

Also, this part should go into the completionHandler, not outside of it.

guard let responseData = data else{
    print("Error: did not receive data")
       return
}