• New computer day!

  • Creating A Twitter Client For OSX – Part 1

    With the upcoming release of the Mac App Store, I can only imagine another gold rush is upon us. Clever Indie developers making money hand over fist while the store as well as developers find their identities. With that being said, I feel that there is a serious lack of interesting (maintained) Twitter clients for OSX. I say “maintained” because Tweetie for OSX is just fantastic, however Twitter said they don’t have any plans for it at this time. So, I want to provide devs with the tools to create an amazing Twitter client for the Mac that I will want to use :)

    Quite some time ago, I began (and never completed) a series on writing a Twitter client for OSX. It was very well received by the development community, however once Twitter switched over to OAUTH, I became too lazy to update it :( . So, I figured a tutorial series for #iDevBlogADay would be the perfect opportunity to complete it.

    So we are going to start from the ground up. In today’s tutorial, we are going walk through getting the initial resources and setting up Twitter to authenticate our application. We will also post a basic tweet.

    Setting Up Twitter

    In order for your application to interface with Twitter, you must register it with them over at http://developer.twitter.com.

    1. Go to http://developer.twitter.com and sign up if needed
    2. Click on Your Apps
    3. Click Register A New App and fill out all of the information about your client
    4. You’re all set!

    Getting Necessary Resources

    I spent a bit of time researching the various options for handling OAUTH and all of the fun stuff that goes along with Twitter integration and found that MGTwitterEngine was the least painful to implement. I say least painful because it has a few quirks of it’s own along with not having the best documentation in the world.

    So after battling for a bit to get the thing compiled, I have figured out the setup process :). You could also read Matt’s installation instructions, but I will regurgitate them here a little differently and hopefully be more clear. So here it is:

    1. Make sure you have git installed. If not, download it for OSX here.
    2. cd to the directory that you want to clone the files to
    3. Clone the MGTwitterEngine repository. Type:

    $ git clone git://github.com/mattgemmell/MGTwitterEngine.git 4. cd into the MGTwitterEngine folder (we will install the dependancies at this level) 5. Now install the dependancies (TouchJSON and OAUTHConsumer). Note: There is an option to use yajl (yet another json library), but I found it a pain to integrate, so we will just throw it out.

    $ git clone git://github.com/schwa/TouchJSON.git

    $ git clone git://github.com/ctshryock/oauthconsumer.git

    Altogether, this is the order of commands you should have:

    <code class=’bash’>$ cd ~/Desktop
    $ git clone git://github.com/mattgemmell/MGTwitterEngine.git
    $ cd MGTwitterEngine
    $ git clone git://github.com/schwa/TouchJSON.git
    $ git clone git://github.com/ctshryock/oauthconsumer.git</code>
    

    Building MGTwitterEngine (What a freakin pain)

    I find it interesting that this project is riddled with errors directly upon download. So much work went into it, yet it’s so challenging to get working.

    Now open up MGTwitterEngine.xcodeproj. You will notice that there are quite a few missing files (they show in red). That’s fine. DELETE THEM ALL…

    1. Delete the yajl group with everything in it
    2. Delete the Twitter YAJL Parsers group and everything in it
    3. Delete OAToken_KeychainExtensions.m and OAToken_KeychainExtensions.h (they are not used)
    4. Delete CJSONDataSerializer.h and CJSONDataSerializer.m
    5. Delete CSerializedJSONData.h and CSerializedJSONData.m
    6. Click the arrow on the OAuthConsumer group and you will notice that the Crypto is missing. We still need this group, but it’s in the wrong place. Delete this group and then open up your MGTwitterEngine folder in Finder. Navigate to MGTwitterEngine->oauthconsumer. Drag the Crypto folder into your project.
    7. We need to change the C Language Dialect to C99. To do this right click on MGTwitterEngine in XCode and click Get Info. Scroll down to C Language Dialect and click the drop down changing it to C99

    8. Finally, we need to tell MGTwitterEngine that we want to use TouchJSON instead of yajl. To do this open up MGTwitterEngineGlobalHeader.h and set TOUCHJSON_AVAILABLE to 1. 9. If you still have any hair left at this point, click Build and Run to and check out the output in the Console 10. If you don’t feel like jumping through all of these hoops you can download my MGTwitterEngine project with all of this fun stuff completed. Download it here.

    Testing MGTwitterEngine

    For today’s tutorial, we will just be displaying our timeline and updating our status using the demo file provided by MGTwitterEngine. In the next tutorial, we will actually be integrating the engine into a new project. So, open up AppController.m in the Demo group. Matt has given us some nice variables to fill in, in order to make this thing work. Let’s update to applicationDidFinishLaunching method to look like the code below:

    <code class=’objc’>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
            // Put your Twitter username and password here:
            NSString *username = @"brandontreb";
        NSString *consumerKey = @"aKKEsJHTDNsv4xVlMHmMqw";
        NSString *consumerSecret = @"oldpeoplenakedcriscotwister";
    
    // Create a TwitterEngine and set our login details.
    twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
    

    [twitterEngine setUsesSecureConnection:NO]; [twitterEngine setConsumerKey:consumerKey secret:consumerSecret]; [twitterEngine setUsername:username]; token = [[OAToken alloc] initWithKey:@“16369316-GgqA00WO0poCAj0XAFhJYDDRthVvWMxTnVyKdfWa1” secret:@“StrongEnoughForAManButMadeForAWoman”]; [twitterEngine setAccessToken:token]; [twitterEngine getHomeTimelineSinceID:0 startingAtPage:0 count:20];

    
    }</code>
    

    So obviously I changed my consumer secret and Access Token Secret. You will need to fill this out with your information. Here is how to obtain them.

    Consumer Key & Consumer Secret

    When logged into http://developer.twitter.com/apps/ , click on the application that you created in the first step:

    Scroll down and you should see the Consumer Key and the Consumer Secret.

    Access Token & Access Token Secret

    In the right column, you should see a link titled “My Access Token”. Click on it.

    Now you should see YOUR Access Token and Access Token Secret

    Have Fun!

    After you copy the tokens, keys, and secrets into the app, you should be able start making calls to Twitter using the engine. Build and run the application at this point and watch your home timeline get output to the console. One thing I want to point out is we are displaying an NSDictionary. That means MGTwitterEngine did all of the parsing for us (using TouchJSON), which is super rad.

    One more thing to try for fun is to update your status. It will even show that you updated it from YOUR application on Twitter. Add the following line and run it again.

    <code class=’objc’>[twitterEngine sendUpdate:@"@brandontreb is a code gangster!  Check out his #iDevBlogADay post on making your own Twitter client here http://bit.ly/gGrZvI"];</code>
    

    Well, that does it for today. Join me next week when I will show you how to move the engine into your own project and we will begin displaying tweets in a basic table view.

    Happy Coding!

    Click Here To Go To Part 2

    —-

    This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, or Twitter.

    Tweet

  • Core Data QuickTip: Inverse Relationships

    One thing I always wondered about Core Data is why the compiler would warn you if you didn’t specify the inverse relationship. After reading through Apple’s docs, they essentially say its to make your database more robust by reinforcing those relationships. Plus, you never know when you may have one thing and need to get to the other.

    After working on a project with an Enormous Core Data database, I found one very useful thing about inverses. When you specify one side of the relationship, core data automatically hooks up the other. Allow me to explain in code.

    Let’s say we have a person object with many pets…

    <code class=’objc’>Person *john = [[Person alloc] init];
    Pet *pet = [[Pet alloc] init];
    // Add the one to many relationship from john to pets
    [john addPetObject:pet];
    
    
    // Add the inverse relationship
    [pet setPerson:john];</code>
    

    So, I was doing this in all of my code and then forgot to one time. However, to my surprise, everything still worked. Why, because once you set up one of the relationships, Core Data automatically handles the other. So, the above code is redundant and could just as easily have been.

    <code class=’objc’>[john addPetObject:pet];</code>
    

    OR

    <code class=’objc’>[pet setPerson:john];</code>
    

    and both directions of the relationship would have been established.

    Not super exciting, but I found it to be pretty handy and also saved me quite a bit of extra code.

    Happy Coding!

    Tweet

  • XCode Shortcut

    When in XCode on a MacBook Pro, doing a 3-finger swipe up will switch between the .h and .m files.

    ⌘-option-up will do the same thing

    Productivity++

    Reblog this post [with Zemanta]

    Tweet

  • XCode Shortcut Cheat Sheet

    Xcode ShortcutsThrough my travels through the internets, I have stumbled upon this amazing reference. It’s a complete set of XCode shortcut commands. Learning some of these commands has drastically improved my efficiency when developing in XCode.

    As a big fan of not using the mouse (yes I’m and Emacs guy), this is invaluable. Download the full size image here. Enjoy!

    Tweet

  • Creating A Twitter Client In Objective-C Client Part 2

    Creating A Twitter Client For OSX – Part 1

    This is part 2 in our series about creating a Twitter client in Objective-C. In case you missed it, here is a link to part 1 of this series.

    In the last tutorial I showed you how to retrieve data from Twitter and display the XML in the Console. Today, we will be focusing on sending messages to Twitter via POST. We will be implementing the code to update our Twitter status. So let’s just dig right in.

    1. Updating The TwitterRequest Header File

    Open up TwitterRequest.h and add the following code (Click the image to enlarge)

    screenshot_16

    We have added two properties. The first isPost will be true when we are calling a method that requires a POST to Twitter. This will be methods such as update_status, follow, etc… Next, the variable requestBody will hold the POST arguments that will be sent to Twitter. These will be things such as status text or friend id.

    Finally, we will be adding a method called statuses_update. The reason I named it this is because that is what the method is called in the Twitter API. Like our friends_timeline method, it takes a delegate and selector to call when the request is complete.

    Important: I didn’t highlight this in the screenshot but make sure you change theRequest from an NSURLRequest to NSMutableURLRequest. It will give us some additional methods to set up the POST.

    2. Updating The Twitter Request Class

    Open up **TwitterRequest.m **and add the following code (Click the image to enlarge):

    screenshot_17

    I’ll start by explaining the status_update method. We first set the global isPost property to true. This will tell the request method to make a POST. The next 2 lines set the callback stuff as we did before. The only new line here is setting the requestBody variable. This is just a string that looks like “status=new twitter status”.

    The addition to the **request **method is what will allow us to POST to Twitter. First, we check if the isPost property is set. This will be true if request is called from our **status_update **method. Next, we call the setHTTPMethod of the request to POST. This is pretty obvious.

    The following line let’s Twitter know the type of data that we are sending to it. Next, we call setHTTPBody to set the body of the request. At some point we will want to URL Encode this string, but that will be for a different tutorial. Just don’t use any special characters such as & and = in your update to Twitter right now. All that is happening on this line is we convert the string to NSData using the **dataUsingEncoding **method of NSString and set it to the HTTPBody.

    The last line just sets the Content-Length property to the length of our string. This is needed to correctly do a POST.

    3. Calling The statuses_update Method To Update Your Twitter Status

    Open up ApplicationDelegate.m and add the following code (click the image to enlarge):

    screenshot_03

    One thing to notice here is I commented out the line to get the friends timeline. This is because having both requests running at the same time with the same request object could cause conflicts. The best way to approch this to create an entirly new TwitterRequest object. I just wanted to keep it short.

    This is pretty straight forward. We call the statuses_update method the same way we called the friends_timeline method except pass in the update text. The information received back from Twitter will look something like this:

    screenshot_01

    It’s basically all of your personal profile information.

    That’s it for today. If you have any comments or questions, feel free to leave them in the comments of this post or write me on Twitter. You can also download the source for this version below.

    Twitter Mac Client Tutorial 2 – Source

    Happy Coding!

    Tweet

subscribe via RSS