Xamarin中的Google Place API照片元数据:Android

时间:2019-01-02 20:31:33

标签: c# xamarin google-api xamarin.android google-places-api

我尝试从Places API获取照片。 主要代码如下:

private void GetPhotos(Intent data)
    {

        var placePicked = PlacePicker.GetPlace(this, data);

        string placeId = placePicked.Id;
        Task photoMetadataResponse = mGeoDataClient.GetPlacePhotos(placeId);
        if (photoMetadataResponse.IsComplete)
        {

            var  photos =(PlacePhotoMetadataResponse) photoMetadataResponse.Result;
            PlacePhotoMetadataBuffer photoMetadataBuffer = photos.PhotoMetadata;
            if (photoMetadataBuffer.Count > 0)
            {
                IPlacePhotoMetadata photoMetaData = (IPlacePhotoMetadata) photoMetadataBuffer.Get(0);
                Task photoResponse = mGeoDataClient.GetPhoto(photoMetaData);
                if (photoResponse.IsComplete)
                {

                    PlacePhotoResponse photoResult = (PlacePhotoResponse) photoResponse.Result;
                    Bitmap bitmap = photoResult.Bitmap;
                }
            }

        }
    }

尝试初始化时遇到问题:

IPlacePhotoMetadata photoMetaData = (IPlacePhotoMetadata) photoMetadataBuffer.Get(0);

例外是:

  

System.InvalidCastException:指定的转换无效。

mGeoDataClient正在等待IPlacePhotoMetadata中的对象。我检查了什么对象photoMetadataBuffer.Get(0)

返回的名称空间为:

  

android.common.data.zzc

该对象并不能告诉我太多...我如何在IPlacePhotoMetadata上投射photoMetadataBuffer?还是我这边会出什么毛病?

1 个答案:

答案 0 :(得分:0)

您应该使用Xamarin的Async包装器,或直接分解基于Android的任务(查看Xamarin包装器使用的TasksExtensions.AsAsync),以获得Android Task返回的正确实例:

Xamarin的异步包装器示例:

private async void GetPhotosAsync(Intent data)
{
    var placePicked = PlacePicker.GetPlace(this, data);

    string placeId = placePicked.Id;
    var photoMetadataResponse = await mGeoDataClient.GetPlacePhotosAsync(placeId);
    var photoMetadataBuffer = photoMetadataResponse.PhotoMetadata;
    if (photoMetadataBuffer.Count > 0)
    {
        var photoMetaData = (IPlacePhotoMetadata)photoMetadataBuffer.Get(0);
        var photoResponse = await mGeoDataClient.GetPhotoAsync(photoMetaData);
        var bitmap = photoResponse.Bitmap;

        ~~~
    }
}

注意:我假设当您获得其余方法时,GetPhotosAsync将返回void之外的其他内容……

更新:

private async void GetPhotos(Intent data)
{
    var placePicked = PlacePicker.GetPlace(this, data);

    string placeId = placePicked.Id;
    using (var photoMetadataResponse = await mGeoDataClient.GetPlacePhotosAsync(placeId))
    using (var photoMetadataBuffer = photoMetadataResponse.PhotoMetadata)
    {
        foreach (var item in photoMetadataBuffer)
        {
            using (var photoResponse = await mGeoDataClient.GetPhotoAsync(item))
            {
                var bitmap = photoResponse.Bitmap;
                photoResponse.Dispose();
            }
            break;
        }
    }
}