在 SWIFT 中收到来自 API 的响应时"<null>"崩溃



从api获取图像url null作为响应,有什么方法可以修复它吗?来自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).valu‌​eForKey("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
    }
}

为什么不简单地使用==like:进行检查

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
        }

最新更新