如何使用photo_reference显示谷歌json响应中的图像



我从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解析链接,我得到了一个形式为的键/值对数据集NSDictionary命名为jsonResponse

NSDictionary*jsonResponse=[NSSONSerialization JSONObjectWithData:数据选项:0 error:&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)
                }
    }

最新更新