繁体   English   中英

iOS Swift-使用API​​的响应

[英]iOS swift - working with response from API

我对Swift和iOS开发非常陌生。 我想知道如果我使用JavaScript怎么做相对简单的事情。

我正在调用返回以下内容的API。 请原谅格式,但是它是直接从Xcode控制台复制的。

["type": success, "value": <__NSArrayI 0x600000030340>(
       {
          categories = ();
          id = 155;
          joke = "Chuck Norris does not &quot;style&quot; his hair. It lays perfectly in place out of sheer terror.";
       },
       {
            categories = (nerdy);
            id = 69;
            joke = "Scientists have estimated that the energy given off during the Big Bang is roughly equal to 1CNRhK (Chuck Norris Roundhouse Kick).";
       }
    )
]

我想循环响应并添加到数组。 在JavaScript中,其外观如下所示:

let jokes = [];
response.value.forEach(item => {
   jokes.push(item.joke)
})

不必完全像上面那样。 我有信心在循环中使用循环并附加到数组。 我正在努力做的是访问从API返回的value数组中的笑话。

我的控制器如下所示:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://api.icndb.com/jokes/random/2")
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                print(json["value"])
                // not sure how to access each joke in the array here
            } catch let error as NSError {
                print(error)
            }
        }).resume()
    }
}

你可以试试

if let va = json["value"] as? [[String:Any]] {
   va.forEach { print($0["joke"]) }
}

我更愿意为此编写一个Codable结构

struct Root: Codable {
    let type: String
    let value: [Value]
}

struct Value: Codable {
    let categories: [Category]
    let id: Int
    let joke: String
}

struct Category: Codable {
}

let res = try? JSONDecoder().decode(Root.self,from:data)
print(res.value)

从日志中可以看到,变量json [“ value”]的类型为NSArray,因此您可以执行类似的操作来获取数据(有很多方法可以执行此操作)。

首先,您可以像这样创建对象笑话

class Joke: NSObject {
     var categories = [String]()
     var id: Int?
     var joke: String?

     init(json: [String: Any]) {
         if let categories = json["categories"] as? String {
             for category in categories {
                 self.categories.append(category)
             }
         }
         if let id = json["id"] as? Int {
             self.id = id
         }
         if let joke = json[""] as? String {
             self.joke = joke
         }
     }
}

然后在ViewController中执行此操作

class ViewController: UIViewController {


    var jokes = [Joke]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://api.icndb.com/jokes/random/2")
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                print(json["value"])
                // not sure how to access each joke in the array here
                let arrayOfObject = json["value"] as! NSArray
                for object in arrayOfObject {
                    if let json = object as? [String: Any] {
                        let object = Joke(json: json)
                        // Now you have your object containing the data from the JSON and you can insert it in your array of Object
                        jokes.append(object)
                    }
                }
            } catch let error as NSError {
                print(error)
            }
        }).resume()
    }
}

记住,有很多方法可以做到这一点,我向您展示了一种简单的方法,希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM