您可以使用 Places SDK for iOS 請求地點相片,在應用程式中顯示。「地點相片」服務傳回的相片取自各種來源,包括業主和使用者提供的相片。如要擷取地點相片,請按照下列步驟操作:
- 呼叫
[GMSPlacesClient fetchPlaceFromPlaceId]
,並傳遞含有地點 ID 和回呼的字串。這會使用GMSPlacePhotoMetadataList
物件呼叫回呼。 - 在
GMSPlacePhotoMetadataList
物件上存取results
屬性,然後從陣列中選取要載入的照片。 - 針對要從這個清單載入的每個
GMSPlacePhotoMetadata
,呼叫[GMSPlacesClient loadPlacePhoto:callback:]
或[GMSPlacesClient loadPlacePhoto:constrainedToSize:scale:callback:]
。 這些函式會使用可用的 UIImage 呼叫回呼。相片寬度或高度上限為 1600 像素。
程式碼範例
下列範例方法會取得地點 ID,並取得傳回清單中的第一張相片。您可以在自己的應用程式中建立方法,並以這個方法做為範本。
Swift
// Specify the place data types to return (in this case, just photos). let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.photos.rawValue))! placesClient?.fetchPlace(fromPlaceID: "INSERT_PLACE_ID_HERE", placeFields: fields, sessionToken: nil, callback: { (place: GMSPlace?, error: Error?) in if let error = error { print("An error occurred: \(error.localizedDescription)") return } if let place = place { // Get the metadata for the first photo in the place photo metadata list. let photoMetadata: GMSPlacePhotoMetadata = place.photos![0] // Call loadPlacePhoto to display the bitmap and attribution. self.placesClient?.loadPlacePhoto(photoMetadata, callback: { (photo, error) -> Void in if let error = error { // TODO: Handle the error. print("Error loading photo metadata: \(error.localizedDescription)") return } else { // Display the first image and its attributions. self.imageView?.image = photo; self.lblText?.attributedText = photoMetadata.attributions; } }) } })
Objective-C
// Specify the place data types to return (in this case, just photos). GMSPlaceField fields = (GMSPlaceFieldPhotos); NSString *placeId = @"INSERT_PLACE_ID_HERE"; [_placesClient fetchPlaceFromPlaceID:placeId placeFields:fields sessionToken:nil callback:^(GMSPlace * _Nullable place, NSError * _Nullable error) { if (error != nil) { NSLog(@"An error occurred %@", [error localizedDescription]); return; } if (place != nil) { GMSPlacePhotoMetadata *photoMetadata = [place photos][0]; [self->_placesClient loadPlacePhoto:photoMetadata callback:^(UIImage * _Nullable photo, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error loading photo metadata: %@", [error localizedDescription]); return; } else { // Display the first image and its attributions. self->imageView.image = photo; self->lblText.attributedText = photoMetadata.attributions; } }]; } }];
快取
使用 [GMSPlacesClient loadPlacePhoto:callback:]
或 [GMSPlacesClient loadPlacePhoto:constrainedToSize:scale:callback:]
載入的相片,會由共用 NSURLCache
中的 Foundation URL 載入系統,快取到磁碟和記憶體中。
如要設定快取行為,您可以在應用程式委派的 application:didFinishLaunchingWithOptions:
方法中,使用 [NSURLCache setSharedURLCache:]
變更共用 URL 快取。
如果您不希望應用程式與 Places SDK for iOS 共用 NSURLCache
,可以建立新的 NSURLCache
,並在應用程式中專門使用這個 NSURLCache
,不必將其設為共用快取。
歸因
在大多數情況下,使用地點相片時可以不包含作者資訊,圖片本身也可能已加入必要的作者資訊。不過,如果傳回的 GMSPlacePhotoMetadata
執行個體包含出處資訊,您每次顯示圖片時就必須在應用程式中另外加入出處資訊。請注意,出處中的連結必須可供輕觸。請參閱出處資訊說明文件。
用量限制
擷取圖片會耗用一個配額單位,擷取相片中繼資料則沒有用量限制。進一步瞭解用量和帳單。