Facebook の次は今はやりの写真共有 SNS Instagram に Xamarin.Forms でアクセスしてみようと思います
まずは Instagram のユーザー登録をして、終わったらログインして下記のページを開きます
Instagram Developer Documentation
緑色の「Register Your Application」ボタンをクリックして
初回は必要事項を入力してまず開発者登録
2回目以降は Instagram にアクセスさせるアプリの必要事項を入力します
ユーザーにログインしてもらってからリダイレクトさせる Uri については、Facebook の汎用ページを借用させていただきました!
登録するとアクセスに必要な各種キーが発行されます
とりあえず今回は OAuth 認証で API を利用できる状態にするところまで作ってみます・・・ 、 いつものように Xamarin.Forms の Portable プロジェクトを作成したら、NuGet で Microsoft.Http と Json.Net のライブラリをインストール、そして Facebook と同じように下記のようなコードを書きました
public partial class TopPage : ContentPage { /// <summary> /// Client ID /// </summary> private const string ClientId = @"Instagram の CLIENT ID を指定"; /// <summary> /// Client Secret /// </summary> private const string ClientSecret = @"Instagram の CLIENT SECRET を指定"; public TopPage() { InitializeComponent(); } /// <summary> /// Page appearing event handler /// </summary> protected override void OnAppearing() { base.OnAppearing(); // Navigate to facebook authorize page this.webView.Source = string.Format( @"https://api.instagram.com/oauth/authorize/?client_id={0}&redirect_uri={1}&response_type=code", ClientId, WebUtility.UrlEncode(@"http://www.facebook.com/connect/login_success.html")); this.webView.Navigating += this.OnNavigating; } /// <summary> /// WebView navigating event handler /// </summary> /// <param name="sender">event sender</param> /// <param name="e">event arguments</param> private async void OnNavigating(object sender, WebNavigatingEventArgs e) { if (e.Url.StartsWith(@"http://www.facebook.com/connect/login_success.html")) { this.webView.Navigating -= this.OnNavigating; var uri = new Uri(e.Url); if (uri.Query.StartsWith("?code=")) { var code = uri.Query.TrimStart('?').Split('&').First().Split('=').LastOrDefault(); var client = new HttpClient(); var content = new FormUrlEncodedContent(new Dictionary<string, string> { {"client_id", ClientId}, {"client_secret", ClientSecret}, {"grant_type", @"authorization_code" }, {"redirect_uri", @"http://www.facebook.com/connect/login_success.html" }, {"code", code }, }); var result = await client.PostAsync(@"https://api.instagram.com/oauth/access_token", content); var json = await result.Content.ReadAsStringAsync(); var response = JsonConvert.DeserializeObject(json); Debug.WriteLine(response); await DisplayAlert("XamarinFacebook", string.Format("Instagram 認証に成功しました, response={0}", response), "OK"); } } }}
Instagram は Facebook と同じ OAuth 2.0 対応なのでほとんど似たような感じですね
Android の場合は、INTERNET のパーミッションを有効にした上でさっそくおためし
さくさくできました!