読者です 読者をやめる 読者になる 読者になる

しっぽを追いかけて

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

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

Xamarin.Forms で写真をアップしながらウォール投稿する

今度は写真と一緒にウォール投稿してみます・・・

/// <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 cancel = new CancellationTokenSource();
            JToken id = null;

            using (var client = new HttpClient())
            {
                // Content-type: multipart/form-data
                using (var data = new MultipartFormDataContent())
                {

                    var parameters = new Dictionary<string, string>
                    {
                        {"caption", @"これは facebook アプリ写真アップロードのテストです"},
                        {"no_story", @"true"},
                        {"privacy", @"{""value"":""SELF""}"},
                    };
                    foreach (var param in parameters)
                    {
                        data.Add(new StringContent(param.Value), param.Key);
                    }

                    // Add photo binary stream data
                    var image = (StreamImageSource)ImageSource.FromResource("XamarinFacebook.Assets.cat.png");
                    data.Add(new StreamContent(await image.Stream.Invoke(cancel.Token)), "image", @"cat.png");


                    var result = await client.PostAsync(
                        string.Format(@"https://graph.facebook.com/me/photos?access_token={0}", token), data,
                        cancel.Token);

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

                    var response = JsonConvert.DeserializeObject(json) as JObject;
                    if (response == null || !response.TryGetValue("id", out id))
                    {
                        return;
                    }
                }
            }

            JToken photoUri = null;

            // Get uri of photo uploaded
            using (var client = new HttpClient())
            {
                var result = await client.GetAsync(
                    string.Format(@"https://graph.facebook.com/{0}?access_token={1}", id.Value<string>(), token),
                    cancel.Token);

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

                var response = JsonConvert.DeserializeObject(json) as JObject;

                if (response == null || !response.TryGetValue("source", out photoUri))
                {
                    return;
                }
            }

            // Publish feed with photo
            using (var client = new HttpClient())
            {
                var data = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    {"message", @"これは facebook アプリ投稿のテストです"},
                    {"link", photoUri.Value<string>()}, // url of updated photo
                    {"picture", photoUri.Value<string>()}, // url of updated photo
                    {"name", @"えきちょうの雄姿、撮った!" },
                    {"caption", @"ねこあつめ" },
                    {"description", @"伝説のえきちょうがついに庭先に現れた!"},
                    {"privacy", @"{""value"":""SELF""}"},
                });

                var result = await client.PostAsync(
                    string.Format(@"https://graph.facebook.com/me/feed?access_token={0}", token), data,
                    cancel.Token);

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

                var response = JsonConvert.DeserializeObject(json) as JObject;
                await DisplayAlert("XamarinFacebook", string.Format("facebook 投稿に成功しました, response={0}", response), "OK");
            }
        }
        else
        {
            // Login failed
            await DisplayAlert("XamarinFacebook", "OAuth 認証に失敗しました", "OK");
        }
    }
}

ちょっと長くなっちゃいました

写真をアップロードしたらその object ID を取得しておいて

JToken photoUri = null;

// Get uri of photo uploaded
using (var client = new HttpClient())
{
    var result = await client.GetAsync(
        string.Format(@"https://graph.facebook.com/{0}?access_token={1}", id.Value<string>(), token),
        cancel.Token);

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

    var response = JsonConvert.DeserializeObject(json) as JObject;

    if (response == null || !response.TryGetValue("source", out photoUri))
    {
        return;
    }
}

アップした写真の Uri を取得

// Publish feed with photo
using (var client = new HttpClient())
{
    var data = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        {"message", @"これは facebook アプリ投稿のテストです"},
        {"link", photoUri.Value<string>()}, // url of updated photo
        {"picture", photoUri.Value<string>()}, // url of updated photo
        {"name", @"えきちょうの雄姿、撮った!" },
        {"caption", @"ねこあつめ" },
        {"description", @"伝説のえきちょうがついに庭先に現れた!"},
        {"privacy", @"{""value"":""SELF""}"},
    });

    var result = await client.PostAsync(
        string.Format(@"https://graph.facebook.com/me/feed?access_token={0}", token), data,
        cancel.Token);

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

    var response = JsonConvert.DeserializeObject(json) as JObject;
    await DisplayAlert("XamarinFacebook", string.Format("facebook 投稿に成功しました, response={0}", response), "OK");
}

さらに link と picture に取得した Uri を設定してウォール投稿しました

f:id:matatabi_ux:20150713234248g:plain

投稿できたかな?

f:id:matatabi_ux:20150713234312p:plain

できました!