0

我正在访问的foursquare api 端点要求我将照片前缀、大小和后缀组合在一起以创建可用的图像URL。我正在尝试在当前有效的“photoURL”常量中执行此操作。

在将变量组合在一起以使用 Haneke 从 URL 设置场所图像视图时,如何检查此 photoURL 的所有部分的数据是否存在(使用 if let)?

这是我的代码:

func bindData() {
    let ratingSignals = self.dog?["venue"]["ratingSignals"].stringValue

    let photoURLPrefix = self.dog?["venue"]["featuredPhotos"]["items"][0]["prefix"].stringValue
    let photoURLSuffix = self.dog?["venue"]["featuredPhotos"]["items"][0]["suffix"].stringValue
    let photoURL = photoURLPrefix! + "original" + photoURLSuffix!
    let venuePhotoURL = NSURL(string: photoURL)

    println("photo url prefix is \(photoURLPrefix)")
    println("photo url suffix is \(photoURLSuffix)")
    println(photoURL)

    self.openUntilLabel.text = self.dog?["venue"]["hours"]["status"].stringValue
    self.addressLabel.text = self.dog?["venue"]["location"]["address"].stringValue
    self.titleLabel.text = self.dog?["venue"]["name"].stringValue
    self.ratingsLabel.text = "Based on \(ratingSignals) ratings"
    self.ratingImageView.image = UIImage(named:"Score8-5")!

    if let photoURL = photoURLPrefix! + "original" + photoURLSuffix!{
        let url = NSURL(string: photoURL)
        venueImageView.hnk_setImageFromURL(url!)
    }

我注释掉了当前有效的 self.venueImageView.hnk_setImageFromURL(venuePhotoURL!),但我担心如果请求不返回图像,它会使应用程序崩溃。因此,我尝试使用 if let 检查数据是否存在,然后在此语句中设置 imageView。

我得到的错误:

“条件绑定中的绑定值必须是可选类型”

这是错误的图像:

在此处输入图像描述

4

2 回答 2

0

我没有运行您的代码,但我认为即使您删除了 if 条件并且如果在没有返回数据的情况下完全阻塞,您的代码也会崩溃。

您应该像这样验证您的回复;

let photoURLPrefix? = self.dog?["venue"]["featuredPhotos"]["items"][0]["prefix"] as String?
let photoURLSuffix? = self.dog?["venue"]["featuredPhotos"]["items"][0]["suffix"] as String?
if (photoURLPrefix == nil || photoURLSuffix == nil)
{
    //Do not proceed
    return;
}

我不知道您从狗对象中检索数据的方式是否有效,但重要的是要使用的可选符号。

于 2015-03-19T19:41:22.413 回答
0

鉴于如果存在前缀,GET 请求将始终返回后缀,我只是针对前缀进行了测试,不需要“组合”它们。

这是我的解决方案: dog(above) 现在是“pin”

if let photoURLPrefix = self.pin?["venue"]["featuredPhotos"]["items"][0]["prefix"].stringValue {
        let photoURLSuffix = self.pin?["venue"]["featuredPhotos"]["items"][0]["suffix"].stringValue
        let photoURL = photoURLPrefix + "original" + photoURLSuffix!
        let venuePhotoURL = NSURL(string: photoURL)
        self.venueImageView.hnk_setImageFromURL(venuePhotoURL!)
        println("photo url prefix is \(photoURLPrefix)")
        println("photo url suffix is \(photoURLSuffix)")
        println(photoURL)
    }
于 2015-03-20T02:27:47.187 回答