如何使用 photo_reference 显示来自 google json 响应的图像?

How to display image from a google json response using photo_reference?

我收到了来自 Google API 的 JSON 回复。但是 JSON 中有一个名为 photo_reference 的标签。如何使用该标签显示图像。

NSDictionary *photoDict = [[place objectForKey:@"photos"] objectAtIndex:0];
NSString *photoRef = [photoDict objectForKey:@"photo_reference"];

NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/photo?photoreference=%@&key=%@&sensor=false&maxwidth=320", photoRef, kGOOGLE_API_KEY];

经过大量研究,我得到了我正在寻找的答案。

想了想,对以后的人有帮助。

步骤:

  1. JSON 解析 link,我得到了一个 key/value 对数据集,形式为 NSDictionary 名为 jsonResponse.

NSDictionary *jsonResponse = [NSJSON序列化JSONObjectWithData:data options:0错误:&error];

  1. 然后,我将键 result 的值存储在另一个 名为 placesResultDictionary 的字典,在给定的代码中 下面。

NSDictionary *result = [jsonResponse valueForKey:@"result"]; NSArray *photos = [placesResultDictionary valueForKey:@"photos"];

            if([photos isKindOfClass:[NSArray class]])
            {
                for (NSDictionary *dictionary in photos)
                {
                    NSString *photoReference = [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"photo_reference"]];
                    NSString *maxWidth = [NSString stringWithFormat:@"%@",[dictionary valueForKeyPath:@"width"]];

                    NSURL *photoURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/photo?maxwidth=%@&photoreference=%@&key=%s",maxWidth,photoReference,GOOGLE_API_KEY]];

                    NSData *photoData = [NSData dataWithContentsOfURL:photoURL];

                    UIImage *image = [UIImage imageWithData:photoData];

                    [place_photos addObject:image];
                }
            }
            else
            {
                UIImage *image = [UIImage imageNamed:@"cell_placeHolder.png"];

                [place_photos addObject:image];
            }

Swift

    if (photos is [Any]) {
                for dictionary: [AnyHashable: Any] in photos {
                    let photoReference: String? = "\(dictionary.value(forKey: "photo_reference") as? String)"
                    let maxWidth: String = "\(dictionary.value(forKeyPath: "width"))"
                    let photoURL = URL(string: "https://maps.googleapis.com/maps/api/place/photo?maxwidth=\(maxWidth)&photoreference=\(photoReference)&key=\(GOOGLE_API_KEY)")
                    let photoData = Data(contentsOf: photoURL)
                    let image = UIImage(data: photoData)
                    place_photos.append(image)
                }
    }