Xamarin.iOS'ta Sosyal Çerçeve

Sosyal Çerçeve, Twitter ve Facebook dahil olmak üzere sosyal ağlarla etkileşim kurmak için birleşik bir API'nin yanı sıra Çin'deki kullanıcılar için DeaWeibo'yu da sağlar.

Sosyal Çerçeve'nin kullanımı, uygulamaların kimlik doğrulamasını yönetmek zorunda kalmadan tek bir API'den sosyal ağlarla etkileşim kurmasını sağlar. Gönderi oluşturmak için sistem tarafından sağlanan bir görünüm denetleyicisinin yanı sıra http üzerinden her sosyal ağın API'sini kullanmana olanak sağlayan bir soyutlama içerir.

Twitter'a bağlanma

Twitter Hesabı Ayarlar

Sosyal Çerçeve'yi kullanarak Twitter'a bağlanmak için, aşağıda gösterildiği gibi cihaz ayarlarında bir hesabın yapılandırılması gerekir:

Twitter Hesabı Ayarlar

Bir hesap Girildi ve Twitter ile doğrulandıktan sonra, cihazda Twitter'a erişmek için Social Framework sınıflarını kullanan tüm uygulama bu hesabı kullanır.

Tweet gönderme

Sosyal Çerçeve, bir tweet'i düzenlemek SLComposeViewController ve göndermek için sistem tarafından sağlanan bir görünüm sunan adlı bir denetleyici içerir. Aşağıdaki ekran görüntüsü bu görünümün bir örneğini gösterir:

Bu ekran görüntüsü SLComposeViewController örneğini gösterir

Twitter ile bir kullanmak için, aşağıda gösterildiği gibi ile yöntemi SLComposeViewController çağrılarak FromService denetleyicinin SLServiceType.Twitter bir örneği oluşturul gerekir:

var slComposer = SLComposeViewController.FromService (SLServiceType.Twitter);

Örnek SLComposeViewController döndürüldikten sonra Twitter'a gönderi yapmak için bir kullanıcı arabirimi sunmak için kullanılabilir. Ancak, ilk olarak çağrısıyla sosyal ağın (bu durumda Twitter) kullanılabilirliğini kontrol IsAvailable etmektir:

if (SLComposeViewController.IsAvailable (SLServiceKind.Twitter)) {
  ...
}

SLComposeViewController hiçbir zaman kullanıcı etkileşimi olmadan doğrudan bir tweet göndermez. Ancak, aşağıdaki yöntemlerle başlatılmış olabilir:

  • SetInitialText – Tweet'te göstermek için ilk metni ekler.
  • AddUrl – Tweete bir URL ekler.
  • AddImage – Tweete bir görüntü ekler.

Başlatıldıktan sonra çağrısı PresentVIewController tarafından oluşturulan görünümü SLComposeViewController görüntüler. Kullanıcı daha sonra isteğe bağlı olarak tweeti düzenleyebilir ve gönderebilir veya göndermeyi iptal edebilir. Her iki durumda da, aşağıda gösterildiği gibi, sonucun tweetin gönderilme veya iptal edilememe durumuna da bakılmak üzere sonucun denetlenmesinde CompletionHandler denetleyicisinin içinde çıkarılmaları gerekir:

slComposer.CompletionHandler += (result) => {
  InvokeOnMainThread (() => {
    DismissViewController (true, null);
    resultsTextView.Text = result.ToString ();
  });
};

Tweet Örneği

Aşağıdaki kodda, tweet göndermek SLComposeViewController için kullanılan bir görünümü sunmak için kullanılarak gösterebilirsiniz:

using System;
using Social;
using UIKit;

namespace SocialFrameworkDemo
{
    public partial class ViewController : UIViewController
    {
        #region Private Variables
        private SLComposeViewController _twitterComposer = SLComposeViewController.FromService (SLServiceType.Twitter);
        #endregion

        #region Computed Properties
        public bool isTwitterAvailable {
            get { return SLComposeViewController.IsAvailable (SLServiceKind.Twitter); }
        }

        public SLComposeViewController TwitterComposer {
            get { return _twitterComposer; }
        }
        #endregion

        #region Constructors
        protected ViewController (IntPtr handle) : base (handle)
        {

        }
        #endregion

        #region Override Methods
        public override void ViewWillAppear (bool animated)
        {
            base.ViewWillAppear (animated);

            // Update UI based on state
            SendTweet.Enabled = isTwitterAvailable;
        }
        #endregion

        #region Actions
        partial void SendTweet_TouchUpInside (UIButton sender)
        {
            // Set initial message
            TwitterComposer.SetInitialText ("Hello Twitter!");
            TwitterComposer.AddImage (UIImage.FromFile ("Icon.png"));
            TwitterComposer.CompletionHandler += (result) => {
                InvokeOnMainThread (() => {
                    DismissViewController (true, null);
                    Console.WriteLine ("Results: {0}", result);
                });
            };

            // Display controller
            PresentViewController (TwitterComposer, true, null);
        }
        #endregion
    }
}

Twitter API'sini çağırma

Sosyal Çerçeve, sosyal ağlara HTTP isteklerinde de destek içerir. İsteği, belirli bir sosyal ağın SLRequest API'sini hedeflemek için kullanılan bir sınıfta kapsüller.

Örneğin, aşağıdaki kod Twitter'a genel zaman çizelgesini almak için bir istekte (yukarıda verilen kodu genişleterek) yapar:

using Accounts;
...

#region Private Variables
private ACAccount _twitterAccount;
#endregion

#region Computed Properties
public ACAccount TwitterAccount {
    get { return _twitterAccount; }
}
#endregion

#region Override Methods
public override void ViewWillAppear (bool animated)
{
    base.ViewWillAppear (animated);

    // Update UI based on state
    SendTweet.Enabled = isTwitterAvailable;
    RequestTwitterTimeline.Enabled = false;

    // Initialize Twitter Account access
    var accountStore = new ACAccountStore ();
    var accountType = accountStore.FindAccountType (ACAccountType.Twitter);

    // Request access to Twitter account
    accountStore.RequestAccess (accountType, (granted, error) => {
        // Allowed by user?
        if (granted) {
            // Get account
            _twitterAccount = accountStore.Accounts [accountStore.Accounts.Length - 1];
            InvokeOnMainThread (() => {
                // Update UI
                RequestTwitterTimeline.Enabled = true;
            });
        }
    });
}
#endregion

#region Actions
partial void RequestTwitterTimeline_TouchUpInside (UIButton sender)
{
    // Initialize request
    var parameters = new NSDictionary ();
    var url = new NSUrl("https://api.twitter.com/1.1/statuses/user_timeline.json?count=10");
    var request = SLRequest.Create (SLServiceKind.Twitter, SLRequestMethod.Get, url, parameters);

    // Request data
    request.Account = TwitterAccount;
    request.PerformRequest ((data, response, error) => {
        // Was there an error?
        if (error == null) {
            // Was the request successful?
            if (response.StatusCode == 200) {
                // Yes, display it
                InvokeOnMainThread (() => {
                    Results.Text = data.ToString ();
                });
            } else {
                // No, display error
                InvokeOnMainThread (() => {
                    Results.Text = string.Format ("Error: {0}", response.StatusCode);
                });
            }
        } else {
            // No, display error
            InvokeOnMainThread (() => {
                Results.Text = string.Format ("Error: {0}", error);
            });
        }
    });
}
#endregion

Şimdi bu koda ayrıntılı olarak bakalım. İlk olarak Hesap Deposuna erişim kazanır ve Twitter hesabının türünü alır:

var accountStore = new ACAccountStore ();
var accountType = accountStore.FindAccountType (ACAccountType.Twitter);

Ardından kullanıcıya, uygulamanın Twitter hesabına erişip erişene sahip olup olamay olduğunu sorar ve erişim izni verildiyse hesap belleğe yüklenir ve kullanıcı arabirimi güncelleştirilir:

// Request access to Twitter account
accountStore.RequestAccess (accountType, (granted, error) => {
    // Allowed by user?
    if (granted) {
        // Get account
        _twitterAccount = accountStore.Accounts [accountStore.Accounts.Length - 1];
        InvokeOnMainThread (() => {
            // Update UI
            RequestTwitterTimeline.Enabled = true;
        });
    }
});

Kullanıcı zaman çizelgesi verilerini isteğinde olduğunda (kullanıcı arabiriminde bir düğmeye dokunarak), uygulama önce Twitter'dan verilere erişmek için bir istek oluşturur:

// Initialize request
var parameters = new NSDictionary ();
var url = new NSUrl("https://api.twitter.com/1.1/statuses/user_timeline.json?count=10");
var request = SLRequest.Create (SLServiceKind.Twitter, SLRequestMethod.Get, url, parameters);

Bu örnek, URL'ye dahil olarak döndürülen sonuçları son on ?count=10 girişle sınırlandırıyor. Son olarak isteği Twitter hesabına (yukarıda yüklenmiş olan) iliştiriyor ve twitter çağrısı gerçekleştiriyor ve verileri getiriyor:

// Request data
request.Account = TwitterAccount;
request.PerformRequest ((data, response, error) => {
    // Was there an error?
    if (error == null) {
        // Was the request successful?
        if (response.StatusCode == 200) {
            // Yes, display it
            InvokeOnMainThread (() => {
                Results.Text = data.ToString ();
            });
        } else {
            // No, display error
            InvokeOnMainThread (() => {
                Results.Text = string.Format ("Error: {0}", response.StatusCode);
            });
        }
    } else {
        // No, display error
        InvokeOnMainThread (() => {
            Results.Text = string.Format ("Error: {0}", error);
        });
    }
});

Veriler başarıyla yüklendi ise ham JSON verileri görüntülenir (aşağıdaki örnek çıktıda olduğu gibi):

Ham JSON veri görüntüsü örneği

Gerçek bir uygulamada JSON sonuçları daha sonra normal şekilde ayrıştırıldı ve sonuçlar kullanıcıya sunuldu. JSON ayrıştırma hakkında bilgi için bkz. Giriş Web Hizmetleri.

Facebook'a bağlanma

Facebook Hesabı Ayarlar

Sosyal Çerçeve ile Facebook'a bağlanmak, yukarıda gösterilen Twitter için kullanılan işlemle neredeyse aynıdır. Cihaz ayarlarında aşağıda gösterildiği gibi bir Facebook kullanıcı hesabının yapılandırılması gerekir:

Facebook Hesabı Ayarlar

Yapılandırıldığında, Cihazda Sosyal Çerçeve'yi kullanan herhangi bir uygulama, Facebook'a bağlanmak için bu hesabı kullanır.

Facebook'a gönderme

Sosyal Çerçeve birden çok sosyal ağa erişmek için tasarlanmış birleşik bir API olduğu için kullanılan sosyal ağ ne olursa olsun kod neredeyse aynı kalır.

Örneğin, tam olarak daha önce gösterilen Twitter örneğinde olduğu gibi kullanılabilir; tek fark Facebook'a özgü SLComposeViewController ayarlara ve seçeneklere geçmektir. Örnek:

using System;
using Foundation;
using Social;
using UIKit;

namespace SocialFrameworkDemo
{
    public partial class ViewController : UIViewController
    {
        #region Private Variables
        private SLComposeViewController _facebookComposer = SLComposeViewController.FromService (SLServiceType.Facebook);
        #endregion

        #region Computed Properties
        public bool isFacebookAvailable {
            get { return SLComposeViewController.IsAvailable (SLServiceKind.Facebook); }
        }

        public SLComposeViewController FacebookComposer {
            get { return _facebookComposer; }
        }
        #endregion

        #region Constructors
        protected ViewController (IntPtr handle) : base (handle)
        {

        }
        #endregion

        #region Override Methods
        public override void ViewWillAppear (bool animated)
        {
            base.ViewWillAppear (animated);

            // Update UI based on state
            PostToFacebook.Enabled = isFacebookAvailable;
        }
        #endregion

        #region Actions
        partial void PostToFacebook_TouchUpInside (UIButton sender)
        {
            // Set initial message
            FacebookComposer.SetInitialText ("Hello Facebook!");
            FacebookComposer.AddImage (UIImage.FromFile ("Icon.png"));
            FacebookComposer.CompletionHandler += (result) => {
                InvokeOnMainThread (() => {
                    DismissViewController (true, null);
                    Console.WriteLine ("Results: {0}", result);
                });
            };

            // Display controller
            PresentViewController (FacebookComposer, true, null);
        }
        #endregion
    }
}

Facebook ile birlikte kullanılırken, Twitter örneğine neredeyse aynı görünen ve bu örnekte başlık olarak SLComposeViewControllerSLComposeViewController gösteren bir görünüm görüntülenir:

SLComposeViewController ekranı

Facebook api'Graph çağırma

Twitter örneğine benzer şekilde, Sosyal Çerçeve'nin nesnesi SLRequest Facebook'un grafik API'si ile kullanılabilir. Örneğin aşağıdaki kod, grafik API'lerinden Xamarin hesabıyla ilgili bilgileri döndürür (yukarıda verilen kodu genişleterek):

using Accounts;
...

#region Private Variables
private ACAccount _facebookAccount;
#endregion

#region Computed Properties
public ACAccount FacebookAccount {
    get { return _facebookAccount; }
}
#endregion

#region Override Methods
public override void ViewWillAppear (bool animated)
{
    base.ViewWillAppear (animated);

    // Update UI based on state
    PostToFacebook.Enabled = isFacebookAvailable;
    RequestFacebookTimeline.Enabled = false;

    // Initialize Facebook Account access
    var accountStore = new ACAccountStore ();
    var options = new AccountStoreOptions ();
    var options.FacebookAppId = ""; // Enter your specific Facebook App ID here
    accountType = accountStore.FindAccountType (ACAccountType.Facebook);

    // Request access to Facebook account
    accountStore.RequestAccess (accountType, options, (granted, error) => {
        // Allowed by user?
        if (granted) {
            // Get account
            _facebookAccount = accountStore.Accounts [accountStore.Accounts.Length - 1];
            InvokeOnMainThread (() => {
                // Update UI
                RequestFacebookTimeline.Enabled = true;
            });
        }
    });

}
#endregion

#region Actions
partial void RequestFacebookTimeline_TouchUpInside (UIButton sender)
{
    // Initialize request
    var parameters = new NSDictionary ();
    var url = new NSUrl ("https://graph.facebook.com/283148898401104");
    var request = SLRequest.Create (SLServiceKind.Facebook, SLRequestMethod.Get, url, parameters);

    // Request data
    request.Account = FacebookAccount;
    request.PerformRequest ((data, response, error) => {
        // Was there an error?
        if (error == null) {
            // Was the request successful?
            if (response.StatusCode == 200) {
                // Yes, display it
                InvokeOnMainThread (() => {
                    Results.Text = data.ToString ();
                });
            } else {
                // No, display error
                InvokeOnMainThread (() => {
                    Results.Text = string.Format ("Error: {0}", response.StatusCode);
                });
            }
        } else {
            // No, display error
            InvokeOnMainThread (() => {
                Results.Text = string.Format ("Error: {0}", error);
            });
        }
    });
}
#endregion

Bu kod ile yukarıda sunulan Twitter sürümü arasındaki tek gerçek fark, Facebook'un, istekte bulunan bir seçenek olarak ayarlandır gereken Geliştirici/Uygulamaya özgü kimliği (Facebook'un Geliştirici Portalı'lerinden oluşturabilirsiniz) alma gereksinimidir:

var options = new AccountStoreOptions ();
var options.FacebookAppId = ""; // Enter your specific Facebook App ID here
...

// Request access to Facebook account
accountStore.RequestAccess (accountType, options, (granted, error) => {
    ...
});

Bu seçenek ayarlanamazsa (veya geçersiz anahtar kullanılırsa) bir hatayla veya veri döndürülecek şekilde sonuçlanmayacaktır.

Özet

Bu makalede, Twitter ve Facebook ile etkileşim kurmak için Sosyal Çerçeve'nin nasıl kullanılası gösterildi. Cihaz ayarlarında her sosyal ağ için hesapların nerede yapılandırıldığından emin oldu. Ayrıca, sosyal ağlara gönderme için SLComposeViewController birleşik bir görünüm sunmak üzere 'nin nasıl kullanılamayacakları da ele alınmıştır. Ayrıca, her sosyal SLRequest ağın API'sini çağıran sınıfını inceledi.