本文介绍了在 Swift 中调用 REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Swift 对 REST API 进行 GET 调用,并尝试遵循许多教程,但无法弄清楚.要么是因为我无法弄清楚如何将所有 Obj-C 转换为 Swift,要么是因为其中一半的方法 n' 已被弃用.有谁知道如何调用,并解析返回的JSON数据?

解决方案

你可以这样做:

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
    }


})

这篇关于在 Swift 中调用 REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 03:52
查看更多