想要向标签显示API数据(Swift,Alamofire)

时间:2017-05-09 00:25:43

标签: ios swift alamofire

我正在使用Alamofire来调用Riot API,我希望显示它所调用的信息。我有get请求正在运行,我只是不知道如何链接到应用程序中的标签。我已经包含了代码的截图!

这只是我正在创建的一个简单的应用程序!

func callAlamo(url: String){
    Alamofire.request(url).responseJSON(completionHandler: {
    response in
    self.pasrseData(JSONData: response.data!)
    })
  }

func parseData(JSONData: Data){
  do {
        var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as? JSONStandard
        print(readableJSON)
}

catch {
    print(error)
  }
}

2 个答案:

答案 0 :(得分:0)

您可以在完成块中设置标签的text属性,基本上是:

func callAlamo(url: String){
    Alamofire.request(url).responseJSON(completionHandler: {
        response in

        // here we say get me a non optional data (otherwise don't do the if)
        if let data = response.data {
            // here we are saying if you can't get me a value (i.e. not nil) for:
            // json (note the try? will give nil if there is an error)
            // name, we get the name out of the json dictionary
            // then go to the else block, where we exit the function
            // Happy case where we values for json and name we now have non optional variables W00t
            guard
            let json = try? self.parseData(JSONData: data),
            let name = json["name"] as? String
                else {
                    print("name does not exist in json: \(json)")
                    return
            }
            // Time to set the label
            self.name.text = name
        }
    })
}

// Changed this to return JSON as a dictionary (it looks like what you printed was a dictionary)
// I also changed this so it throws the error and doesn't deal with it.
// It probably doesn't know what to do if it can't read json something
// else should handle the error higher up the stack

func parseData(JSONData: Data) throws -> [String: Any]? {
    return try JSONSerialization.jsonObject(with:
    JSONData, options: .mutableContainers) as? [String: Any]
}

注意:如果您遇到问题并且我会选择经过测试的解决方案,这是未经测试的。

编辑:回答如何获得其他财产。

我们的方式"名称"是这块代码:

guard
let json = try? self.parseData(JSONData: data),
let name = json["name"] as? String
    else {
        print("name does not exist in json: \(json)")
        return
}

要获得另一处房产,我们可以这样做:

guard
let json = try? self.parseData(JSONData: data),
let name = json["name"] as? String,
let summonerLevel = json["summonerLevel"] as? Int

    else {
        print("name does not exist in json: \(json)")
        return
}

然后显示summonerLevel我们和name一样(虽然我们有一个int而不是String)

// Time to set the label
self.name.text = name
// (you will have to create this new label)
self.summonerLevelLabel.text = "Level: \(summonerLevel)"

答案 1 :(得分:0)

无需序列化,因为来自Alamofire的responseJSON已完成此操作。由于我不知道你的JSON对象里面是什么,让我们说你得到了年龄和名字的回报:

struct InfoModel { // this struct will decompose our JSON object from the response that we get 
    var age:Int
    var name:String
    init(json:Dictionary<String,Any>?) { 
        guard let dict = json,
        let age = dict["age"] as? Int,
        let name = dict["name"] as? String
            else {fatalError() }
        self.age = age
        self.name = name

    }
}

func parse(url: String, completion:@escaping (InfoModel)-> Void) {
    Alamofire.request(url).responseJSON {response in
        // get the JSON dictionary
        if let JSON = response.result.value {
            // no need to decompose your object since your struct does it inside of its initializer
            completion(InfoModel(json: JSON as? Dictionary<String, Any>))
        }
    }
}
// call this function anywhere
parse(url: "") { (m:InfoModel) in
   print("age= \(m.age), name= \(m.name)")
   // now populate your label 
   labelOne.text = "\(m.age)"
   labelTwo.text = name
}