しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Xamarin.Forms で Facebook のウォールに投稿してみる

前回 は単にユーザー情報を取得するだけでしたが、今度はウォール投稿を試してみます

コードはこんな感じ

/// <summary>
/// Page appearing event handler
/// </summary>
protected override void OnAppearing()
{
    base.OnAppearing();

    // Navigate to facebook authorize page
    this.webView.Source = string.Format(@"https://m.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&response_type=code,token&scope=publish_actions",
        AppId,
        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 (!string.IsNullOrEmpty(uri.Fragment) && uri.Fragment.StartsWith("#access_token"))
        {
            var token = uri.Fragment.Split('&').First().Split('=').LastOrDefault();

            var client = new HttpClient();
            var content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"message", @"これは facebook アプリ投稿のテストです"},
                {"link", @"http://www.gizmodo.jp/2015/07/post_17525.html"},
                {"name", @"ねこパンチが生態系を脅かす? 飼い主のある行動が、人類の未来に繋がるかも!" },
                {"caption", @"ギズモード・ジャパン" },
                {"description", @"家で飼っている猫、「外に出してー」と言わんばかりに、にゃーにゃー鳴いたことはありませんか?"},
                {"privacy", @"{""value"":""SELF""}"},
            });
            var result = await client.PostAsync(
                string.Format(@"https://graph.facebook.com/me/feed?access_token={0}", token), content);

            var json = await result.Content.ReadAsStringAsync();

            var response = JsonConvert.DeserializeObject(json);

            Debug.WriteLine(response);

            await DisplayAlert("XamarinFacebook", string.Format("facebook 投稿に成功しました, response={0}", response), "OK");
        }
        else
        {
            // Login failed
            await DisplayAlert("XamarinFacebook", "OAuth 認証に失敗しました", "OK");
        }
    }
}
    // Navigate to facebook authorize page
    this.webView.Source = string.Format(@"https://m.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&response_type=code,token&scope=publish_actions",
        AppId,
        WebUtility.UrlEncode(@"http://www.facebook.com/connect/login_success.html"));

最初のログイン時に scope=publish_actions を追加しました

            var client = new HttpClient();
            var content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                {"message", @"これは facebook アプリ投稿のテストです"},
                {"link", @"http://www.gizmodo.jp/2015/07/post_17525.html"},
                {"name", @"ねこパンチが生態系を脅かす? 飼い主のある行動が、人類の未来に繋がるかも!" },
                {"caption", @"ギズモード・ジャパン" },
                {"description", @"家で飼っている猫、「外に出してー」と言わんばかりに、にゃーにゃー鳴いたことはありませんか?"},
                {"privacy", @"{""value"":""SELF""}"},
            });
            var result = await client.PostAsync(
                string.Format(@"https://graph.facebook.com/me/feed?access_token={0}", token), content);

あとは POST で https://graph.facebook.com/me/feed に向けて必要な情報を Key-Value 型のコレクションで渡すだけ

動かしてみました

f:id:matatabi_ux:20150708073643g:plain

ちゃんと投稿できているか確認

f:id:matatabi_ux:20150708073756p:plain

大丈夫みたいですね!