Geeks With Blogs

Joe Mayo

The Twitter API recently deprecated the statuses/update_with_media endpoint, which LINQ to Twitter abstracts via a TweetWithMedia method. It’s replaced with a new endpoint, media/upload, and a new parameter to statuses/update, media_ids. The benefit of the new API change is that you can now tweet multiple images. Naturally, LINQ to Twitter supports this capability. However, what’s really interesting is that you can upload multiple images at the same time with Task.WhenAll. This post explains how to do this.

Uploading Images

The first step to tweeting multiple images is to upload the images you need. You can do this with LINQ to Twitter’s new UploadMediaAsync method, like this:

    Media uploadedMedia = await twitterCtx.UploadMediaAsync(File.ReadAllBytes(@"..\..\images\200xColor_2.png"))

The UploadMediaAsync method takes a byte[] and returns a Media instance. The Media instance is important because it contains a MediaID that Twitter assigned to identify the uploaded image. You’ll see how to use this in a later section of this post. As with all other LINQ to Twitter commands and queries, UploadMediaAsync runs asynchronously.

Uploading Multiple Images in Parallel

You can upload multiple images in parallel via the Task.WhenAll method, which accepts a collection of Task<TResult>. Here’s how to upload multiple images in parallel to Twitter:

            var imageUploadTasks = 
                new List<Task<Media>> 

            await Task.WhenAll(imageUploadTasks);

This example creates a List of Task<Media> and awaits Task.WhenAll. This causes the program to pause, waiting for the three invocations of UploadMediaAsync to complete. When each method completes, Task.WhenAll returns. You then need to associate these images with a tweet.

Tweeting Multiple Images

Once each method completes and Task.WhenAll returns, you can tweet the images. The following code gets a list of MediaID that Twitter returns and performs a tweet that includes the uploaded images:

            var mediaIds =
                (from tsk in imageUploadTasks
                 select tsk.Result.MediaID)

            Status tweet = await twitterCtx.TweetAsync(status, mediaIds);

The UploadMediaAsync method returns a Media instance that contains a MediaID that Twitter uses to identify each uploaded image. In the code above, you can see how to pull those values from the collection that was originally passed to Task.WhenAll, imageUploadTasks. Then use the new overload of TweetAsync to pass that list, mediaIds, as a parameter (with tweet text in the status parameter).

This results in a tweet that contains text and will display the three images uploaded.

For more info on Twitter API constraints and details of the multi-image process, visit the Twitter API documentation, Uploading Media: Multiple Photos.



Posted on Tuesday, October 21, 2014 11:34 PM Twitter , LINQ to Twitter , Multi-Threading , Async | Back to top

Copyright © Joe Mayo | Powered by: