は、基本的には、完成ブロックにラベルのテキストプロパティを設定します。
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]
}
NB:あなたの持つ問題と私がテストしたソリューションのために行く場合、これは未テストです。
編集:別のプロパティを取得する方法を回答します。
私たちは、「名前」を得た方法は、このコードの塊だった:
guard
let json = try? self.parseData(JSONData: data),
let name = json["name"] as? String
else {
print("name does not exist in json: \(json)")
return
}
別のプロパティを取得するには、我々はこれを行うことができます:私たちは同じ操作を行うsummonerLevel表示するには、次に
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
}
を名前付き(ただし文字列ではありません)
// Time to set the label
self.name.text = name
// (you will have to create this new label)
self.summonerLevelLabel.text = "Level: \(summonerLevel)"
コードを表示してください。 –
編集したオリジナルのテキスト、コンソールレスポンスのスクリーンショットを開く –