[英]Unable to get jsondata in swift 3?
在這里我需要檢查鍵img_type
的值如果它是 1 然后我需要獲取img_file
的鍵值對如果不是 2 然后我需要獲取鍵值對img_url
但是我在檢查我得到的值時卡在這里這段代碼的錯誤誰能幫我實現這個?
{
"id": "1",
"name": "banner1",
"status": "1",
"display_from": null,
"display_to": null,
"img_type": "1",
"img_file": "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg",
"img_url": "",
"img_title": "banner1",
"img_alt": "banner1",
"url": "",
"is_open_url_in_new_window": "1",
"is_add_nofollow_to_url": "1"
},
{
"id": "5",
"name": "banner5",
"status": "1",
"display_from": null,
"display_to": null,
"img_type": "2",
"img_file": "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/",
"img_url": "https://www.dtelepathy.com/blog/wp-content/uploads/2015/06/Technique-for-Faster-Web-Development.jpg",
"img_title": "",
"img_alt": "",
"url": "",
"is_open_url_in_new_window": "1",
"is_add_nofollow_to_url": "1"
}
func bannerDownloadJsonWithURL(){
let url = URL(string: bannerUrl)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil { print(error!); return }
do {
if let jsonObj = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
for item in jsonObj {
if let itemDict = item as [String:Any]! {
for item in itemDict {
if item.key["img_type"] == 1 {
}
}
}
}
DispatchQueue.main.async {
}
}
} catch {
print(error)
}
}
task.resume()
}
你必須像下面這樣使用:
if let itemDict = item as [String:Any]! {
if let imgTypeString = itemDict["img_type"] as? String, let imgType = Int(imgTypeString) {
if imgType == 1 {
print("img_file", itemDict["img_file"])
} else if imgType == 2 {
print("img_url", itemDict["img_url"])
}
} else {
print("Unable to parse img_type")
}
}
item.key["img_type"]
是從鍵中獲取值的錯誤方法。 要么使用item["img_type"]
來獲取item.objectForKey("img_type")
。
if let itemDict = item as [String:Any]!
{
for item in itemDict
{
let diction = item as [String:Any]!
let imageType = diction["img_type"] as! String
if Int(imageType) == 1
{
}
}
}
還要檢查img_type
值的數據類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.