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

时间:2015-07-02 07:44:09

标签: ios objective-c json google-api

我从Google API获得JSON响应。但JSON中有一个名为photo_reference的标签。如何使用该标签显示图像。

2 个答案:

答案 0 :(得分:1)

Queue

答案 1 :(得分:0)

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

思想,将来会对某人有所帮助。

步骤:

  1. JSON解析链接,我得到了一个键/值对数据集 NSDictionary 名为 jsonResponse
  2. NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:数据选项:0错误:&错误];

    1. 然后,我将密钥 结果 的值存储在另一个中 字典名为placesResultDictionary,它位于给定的代码中 下方。
    2. NSDictionary * result = [jsonResponse valueForKey:@" result"];     NSArray * photos = [placesResultDictionary valueForKey:@"照片"];

                  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];
                  }
      

      <强>夫特

          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)
                      }
          }