且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Swift 中调用 REST API

更新时间:2022-10-14 22:39:13

你可以这样做:

var url : String = "http://google.com?test=toto&test2=titi"无功请求:NSMutableURLRequest = NSMutableURLRequest()request.URL = NSURL(string: url)request.HTTPMethod = "GET"NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void invar 错误:AutoreleasingUnsafeMutablePointer<NSError?>= 零让 jsonResult: NSDictionary!= NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as?NSD字典如果(jsonResult != nil){//处理jsonResult} 别的 {//无法加载 JSON,查看错误}})

对于有此问题的人,您的 JSON 流可能是一个数组 [] 而不是对象 {},因此您必须将 jsonResult 更改为NSArray 而不是 NSDictionary

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 translate all the Obj-C to Swift, or because half of the methods n' such are deprecated. Does anyone know how to make the call, and parse returned JSON data?

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


})

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