Xamarin谷歌日历示例

时间:2018-03-05 03:11:24

标签: c# xamarin uwp google-calendar-api

我试图让这个样本使用Xamarin(Xamarin Forms)

https://developers.google.com/google-apps/calendar/quickstart/dotnet

我修改了代码,以便Xamarin Forms应用程序从资源文件加载凭据json。我通过单步执行代码来检查资源文件是否已加载。我还修改了DataStore类,因为Xamarin Forms无法访问示例中指定的路径。

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestXamarinFormsLibrary.Pages
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CalendarPage : ContentPage
    {
        public CalendarPage()
        {
            InitializeComponent();
            Go();
        }

        static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
        static string ApplicationName = "Google Calendar API .NET Quickstart";

        private async void Go()
        {
            UserCredential credential;

            var assembly = GetType().Assembly;
            using (var stream = assembly.GetManifestResourceStream("TestXamarinFormsLibrary.client_secret.json"))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new DataStore()).Result;
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 10;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    string when = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }
                    await DisplayAlert("ok", $"{eventItem.Summary} ({when})", "ok");
                }
            }
        }
    }

    public class DataStore : IDataStore
    {
        private Dictionary<string, object> Data = new Dictionary<string, object>();

        public Task ClearAsync()
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync<T>(string key)
        {
            throw new NotImplementedException();
        }

        public async Task<T> GetAsync<T>(string key)
        {
            if (Data.ContainsKey(key))
            {
                return (T)Data[key];
            }

            return default(T);
        }

        public async Task StoreAsync<T>(string key, T value)
        {
            Data.Add(key, value);
        }
    }
}

这是我运行时遇到的错误:

enter image description here

没有例外。我在Android上遇到了类似的错误。我的猜测是它依赖于oAuth库来打开Web浏览器,尝试允许身份验证,但Xamarin Forms不会实现此行为。我也尝试过启用所有UWP功能,但这并没有帮助。

如何让Xamarin Forms运行示例?

2 个答案:

答案 0 :(得分:0)

.NET客户端的repo在这里: https://github.com/google/google-api-dotnet-client

我想我可以从源代码中弄清楚这一点,但我还没有尝试过这个。

答案 1 :(得分:0)

我的UWP应用中有Google .NET客户端。诀窍是您必须将其放入.NET Standard 2.0类库中,公开所需的API服务,然后从UWP应用中引用该库。

此外,您还必须自己获取auth令牌。不需要太多工作,并且Drive API和Calendar API可以正常工作(我尝试过的唯一方法)。您可以看到,我将一个包含auth令牌和其他auth详细信息的简单类传递给名为$doCheck的方法。

这是我在.NET Standard 2.0类库中使用的单个类:

Initialize

此处提供有关UWP的完整答案: https://stackoverflow.com/a/53971436/1938624