Ios 要将API数据显示到标签(Swift、Alamofire)
我正在使用Alamofire调用Riot API,我想显示它调用的信息。我的get请求正在工作,我只是不知道如何链接到应用程序中的标签。我已经包括了代码的截图Ios 要将API数据显示到标签(Swift、Alamofire),ios,swift,alamofire,Ios,Swift,Alamofire,我正在使用Alamofire调用Riot API,我想显示它调用的信息。我的get请求正在工作,我只是不知道如何链接到应用程序中的标签。我已经包括了代码的截图 这只是我正在创建的一个简单应用程序 func callAlamo(url: String){ Alamofire.request(url).responseJSON(completionHandler: { response in self.pasrseData(JSONData: response.dat
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)
}
}
在完成块中设置标签的文本属性,基本上是:
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
}
然后,为了显示召唤级别,我们使用与name相同的方法(尽管我们使用的是int而不是字符串)
无需序列化,因为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
}
struct InfoModel{//此结构将根据我们得到的响应分解JSON对象
变量年龄:Int
变量名称:String
init(json:字典?{
guard let dict=json,
让age=dict[“age”]as?Int,
让name=dict[“name”]作为字符串
else{fatalError()}
self.age=年龄
self.name=名称
}
}
func解析(url:String,completion:@escaping(InfoModel)->Void){
请求(url).responseJSON{response in
//获取JSON字典
如果让JSON=response.result.value{
//不需要分解对象,因为您的结构在其初始值设定项中进行分解
完成(InfoModel(json:json作为字典))
}
}
}
//在任何地方调用此函数
在中解析(url:){(m:InfoModel)
打印(“年龄=\(m.age),姓名=\(m.name)”)
//现在填充标签
labelOne.text=“\(m.age)”
labelTwo.text=名称
}
请向我们展示您的代码。编辑原始文本,打开控制台响应的屏幕截图。这是一种享受!另一个问题是,json中还有另一个类似于“name”的条目,但它是“callerslevel”,我该如何添加它呢?还有一种序列化json的方法比使用Alamofire更好!如果你愿意,我会送一个例子过来。
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
}