Close

October 28, 2013

Posting a photo to Twitter in Windows Phone

In my previous post, I described how to authenticate your Windows Phone app to Twitter, without using TweetSharp. Now that we’re set up, posting a status to Twitter is fairly easy (see below, after code for posting photo). But posting a photo is a little more challenging. Once again, we’ll be using the Hammock library by Daniel Crenna.First, we need to set a few things up:

var twitterUser = new TwitterUserQuery().Get();
_credentials = new OAuthCredentials
{ 
    Type = OAuthType.ProtectedResource, 
    SignatureMethod = OAuthSignatureMethod.HmacSha1, 
    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader, 
    ConsumerKey = TwitterSettings.ConsumerKey, 
    ConsumerSecret = TwitterSettings.ConsumerKeySecret, 
    Token = twitterUser.AccessToken, 
    TokenSecret = twitterUser.AccessTokenSecret, 
    Version = TwitterSettings.OAuthVersion
};

_client = new RestClient
{ 
    Authority = "http://api.twitter.com", 
    HasElevatedPermissions = true
};

var mediaLibrary = new MediaLibrary();
latestPicture = mediaLibrary.Pictures
    .Where(x => x.Name.Contains("PixImg"))
    .OrderByDescending(x => x.Date)
    .FirstOrDefault();

if (_latestPicture == null)
{ 
    // TODO handle case where no pictures have been taken yet
}

var bitmapImage = new BitmapImage();
bitmapImage.SetSource(_latestPicture.GetImage());
Image.Source = bitmapImage;

What we’re doing here is getting the Twitter data we saved in the previous post. With that, we can create the necessary credentials. Then, we take a picture from our Windows Phone media library and show it to the user.When the user clicks the Tweet button, we need to make a new REST request:

private void OnTweetButtonClicked(object sender, EventArgs e)
{
    var twitterRequest = new RestRequest 
    {
        Credentials = _credentials, 
        Path = "/1.1/statuses/update_with_media.json", 
        Method = WebMethod.Post 
    }; 

    twitterRequest.AddParameter("status", TweetTextBox.Text);
    twitterRequest.AddFile("media[]", _latestPicture.Name, _latestPicture.GetImage(), "image/jpeg");

    _client.BeginRequest(twitterRequest, NewTweetCompleted);
}

That’s actually all there’s to it. If you just want to post a status, leave out the media-parameter and change the path to /1.1/statuses/update.json. Now, when the request is completed, I just navigate back:

private void NewTweetCompleted(RestRequest request, RestResponse response, object userstate)
{ 
    // We want to ensure we are running on our thread UI 
    Deployment.Current.Dispatcher.BeginInvoke(() => 
    { 
        if (response.StatusCode == HttpStatusCode.OK) 
        {
            if (NavigationService.CanGoBack) 
            { 
                NavigationService.GoBack(); 
            } 
            else 
            { 
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); 
            } 
        } 
        else 
        { 
            MessageBox.Show("There was an error connecting to Twitter"); 
        } 
    });
}

If you’re interested, you can check my code on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.