[英]Getting crash when “<null>” as response from api is received in SWIFT
Getting the image url null as response from api, is there any way for fix it. 获取图像url null作为来自api的响应,是否有任何方法可以解决它。 Response from api is:
来自api的回复是:
"image_path" = "<null>";
Tried to handle it like this: 试图像这样处理它:
if !(arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") is NSNull) {
// optional is NOT NULL, neither NIL nor NSNull
}
It is still crashing please guide. 它还在崩溃请指导。 Update:
更新:
Found the problem, null was not the issue actually. 发现问题,null实际上不是问题。 Posting the response below to make things clear.
发布以下回复以明确说明。
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";
}
);
This is the normal response, now the response where trouble is: 这是正常的响应,现在是麻烦的响应:
media = (
);
Can it be handle any how? 可以处理任何方式吗? Please guide.
请指导。
Try like this .. it'll not crash 试试这样..它不会崩溃
if let imgPath = arrList.objectAtIndex(indexPath.row).valueForKey("media")?.objectAtIndex(0).valueForKey("image_path") as? String {
//... your value is string
}
Let me guess types by information you provided: 让我根据您提供的信息猜测类型:
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
}
Validating your string can be like this: 验证您的字符串可以是这样的:
if !image_path.isEmpty && image_path != "<null>" {
//do something
}
or like this: 或者像这样:
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"
}
also try this 也尝试这个
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.