Make REST API call in Swift

前端 未结 15 1327
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:20

I\'m trying to use Swift to make a GET call to a REST API, and have tried to follow numerous tutorials, but can\'t figure it out. Either because I cannot figure out how to

15条回答
  •  [愿得一人]
    2020-12-02 04:54

    You can do like this :

    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 = 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
        }
    
    
    })
    

    EDIT : For people have problem with this maybe your JSON stream is an array [] and not an object {} so you have to change jsonResult to NSArray instead of NSDictionary

提交回复
热议问题