[英]Getting crash when “<null>” as response from api is received in SWIFT
獲取圖像url null作為來自api的響應,是否有任何方法可以解決它。 來自api的回復是:
"image_path" = "<null>";
試圖像這樣處理它:
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
}
它還在崩潰請指導。 更新:
發現問題,null實際上不是問題。 發布以下回復以明確說明。
media = (
{
id = "97eb48a0-429a-11e6-873c-ad7b848648f1";
"image_path" = "https://s3-eu-west-1.mazws.com/facebook_profile_images/15105131.png";
"room_post_id" = "97c572e0-429a-11e6-b72b-fd489f63a1fc";
"user_id" = "66fe22a0-4296-11e6-a1d9-69dc307add4b";
"video_path" = "<null>";
},
{
id = "981a6880-429a-11e6-b039-736a0bf954dc";
"image_path" = "<null>";
"room_post_id" = "97c572e0-429a-11e6-b72b-fd489f63a1fc";
"user_id" = "66fe22a0-4296-11e6-a1d9-69dc307add4b";
"video_path" = "https://s3-eu-west-1.naws.com/facebook_profile_images/1255803.mp4";
}
);
這是正常的響應,現在是麻煩的響應:
media = (
);
可以處理任何方式嗎? 請指導。
試試這樣..它不會崩潰
if let imgPath = arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") as? String {
//... your value is string
}
讓我根據您提供的信息猜測類型:
if let arrList = arrList as? NSArray,
firstObject = arrList.objectAtIndex(indexPath.row) as? NSDictionary,
media = firstObject.valueForKey("media") as? NSArray,
secondObject = media.objectAtIndex(0) as? NSDictionary,
image_path = secondObject.valueForKey("image_path") as? String {
print(image_path)
// now validate your string
}
驗證您的字符串可以是這樣的:
if !image_path.isEmpty && image_path != "<null>" {
//do something
}
或者像這樣:
if !image_path.isEmpty {
if let image_pathURL = NSURL(string: image_path), _ = image_pathURL.host {
//do something
}
}
為什么不用==來簡單檢查:
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") == "<null>")
if let image = myJson["image_path"] as? String {
imageView.image = image
}
else {
imageview.image = "default.png"
}
也嘗試這個
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") == "<null>") {
// optional is NOT NULL, neither NIL nor NSNull
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.