Categories
iPhone app

Calling restful POST PUT and DELETE methods in AFNetworking 2.0

Reading Time: 2 minutes

(Note 12-03-2015): for a more deep understanding of REST API and iOS usage of it, see this blog post by Mugunth Kumar. Very well written piece on REST. My tutorial below is meant to get hands dirty quickly on iOS web service calls 🙂

(Original 09-03-2014) Some example code here. For GET methods and AFNetworking 2.0 using a php web service, raywenderlich.com has an excellent tutorial. One problem I saw when I did this exercise is the service was expecting “application/json” for “Content-Type” (note the default is text/html, if we don’t specify in request serializer).


// POST method
-(IBAction)addBook:(id)sender
{
    // 1, note this is the base URL, typically it's the end point of REST web service
    NSURL *baseURL = [NSURL URLWithString:BaseURLString];
    NSDictionary *parameters = @{@"title": @"One Flew Over the Cuckoo's Nest",
                                 @"author": @"Ken Kesey",
                                 @"read": @false};
    
    // 2
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:@"/book" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        self.title = @"Book added";
        _textView.text = [[NSString alloc] initWithFormat:@"Response JSON: %@", (NSDictionary *)responseObject];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"\n============== ERROR ====\n%@",error.userInfo);
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error adding book"
                                                                message:[error localizedDescription]
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
        [alertView show];
    }];
}

- (void)setupForRemoveAndUpdateBook:(AFHTTPSessionManager **)manager_p bookIdString_p:(NSString **)bookIdString_p
{
    NSURL *baseURL = [NSURL URLWithString:BaseURLString];
    
    [_textField resignFirstResponder];
    
    int bookId = [_textField.text intValue];
    
    *bookIdString_p = [NSString stringWithFormat:@"/book/%i", bookId];
    
    *manager_p = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    (*manager_p).requestSerializer = [AFJSONRequestSerializer serializer];
    (*manager_p).responseSerializer = [AFJSONResponseSerializer serializer];
}

// DELETE method
- (void)remove_book
{
    NSString *bookIdString;
    AFHTTPSessionManager *manager;
    [self setupForRemoveAndUpdateBook:&manager bookIdString_p:&bookIdString];
    
    [manager DELETE:bookIdString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        self.title = @"Book deleted";
        _textView.text = [[NSString alloc] initWithFormat:@"Response JSON: %@", (NSDictionary *)responseObject];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"\n============== ERROR ====\n%@",error.userInfo);
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error deleting book"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];
}

-(IBAction)removeBook:(id)sender
{
    [self clear:nil];

    if (_textField.text == NULL || _textField.text.length==0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Book ID required"
                                                            message:@"Please input the book ID"
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    else {
        [self remove_book];
    }
}

// PUT method
- (void)update_book
{
    NSString *bookIdString;
    AFHTTPSessionManager *manager;
    [self setupForRemoveAndUpdateBook:&manager bookIdString_p:&bookIdString];
    
    NSDictionary *parameters = @{@"read": @true};
    
    [manager PUT:bookIdString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        self.title = @"Book updated";
        _textView.text = [[NSString alloc] initWithFormat:@"Response JSON: %@", (NSDictionary *)responseObject];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"\n============== ERROR ====\n%@",error.userInfo);
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error updating book"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];
}

-(IBAction)updateBook:(id)sender
{
    [self clear:nil];

    if (_textField.text == NULL || _textField.text.length==0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Book ID required"
                                                            message:@"Please input the book ID"
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }
    else {
        [self update_book];
    }
}

Categories
iOS

Announcing iDataGrid ~ a place dedicated to data grid table on iOS

Reading Time: < 1 minute

A little over a year ago, I started working full time as iOS developer for a mining company. One of the first projects is create spreadsheet like application on iPad. At that time there is no UICollectionView, and I found GMGridView to be interesting. I did look at an existing product called iOS Data Grid Table but there are two limitations which prevents me from using it: 1) It displays the values only (read only); 2) Perhaps more important, at that time I don’t recall it includes source code. So I ends up creating my own spreadsheet like tables based on GMGridView. I also read the nice work done by Tom Thompson. Of course that time my knowledge on UITextField (and UITableView for that matter) is not very good, and I did not understand all good work he did. I did used the UIPicker in my project, as it helps the user input data in many cases (simplify/ease input, reduce validation), I believe I borrow some idea from RayWenderlich’s tutorial too (UIPopupController and UIPicker).

A year and half later, when I took another look at this thing, I found at least four new things which are interesting, the shinobi controls (commerical), the MDSpeadView (looks like read only, github, open source), nucliOS (by Infragistics, commercial) and UICollectionView (Apple iOS native, tutorial by RayWenderlich.com)

Categories
iPhone app

Some tips when creating WCF web service for iPad consumption

Reading Time: < 1 minute

Continuation of previous post.

1) WCF get does not like “NULL” column in the query results

2) // note the “id” should match in declaration and method

Categories
iPhone app

Back from Voices that matter: iPhone developer conference

Reading Time: 3 minutes

#VTM_iPhone

The conference was hold in Philadelphia, PA. Note there was a VTM_iPhone conference this past spring in Seattle. This is my first time attending an Apple themed conference, my first time to hear names like Omni Group, Mike Lee, which are almost like household names in Mac/iOS community.

Ok, let me get to the topic, the people and topics of conference. First I want to thank Chuck and Barbara (and all other Pearson Publishing organizers, venue helpers) for their hard work on logistics (food, drink, website etc.), if there is anything could be improved, I think it’s the Wifi access point. Probably due to the overwhelming of iPhone/iPad, and laptop, sometimes we had difficulty connecting to Wifi. But that’s a minor thing, compared the quality of speakers, and the openness atmosphere of participants (Mac community is much friendly than some of the other dev community as I know of).

Technical sessions are excellent, sometimes I had hard time to make a choice but I like to attend all 3 sessions running at the same time. Eventually I decided to take more UI (user interface) and Graphics Design classes as that is my weakness, coming from coder/programmer background and not graphics Q. Here is the schedule of classes. Some of the highlights: Aaron Hillegass talked about the product cycle and going form “independence to interdependence” as business grow. Not entirely new topic, but good reminder to me. Mike Lee reminds me a Chinese guy names Lu Xun (after I gave it more thought): he fired at a lot of places and I think many of his points are valid criticism of “lack of effort/thoughts” in design. I think yesterday Steve Jobs’ fire at Android fragmentation is along the same line. When “Open” is just for business and marketing purpose, how meaningful really is open of Android?

Categories
iPhone app Software development

iPhone iOS dev blogs

Reading Time: 2 minutes

The following are iPhone development blogs I often read. Note I used Google reader to get them. I also listed some of the blogs under “dev” category in the side bar (small).

Technical
iPhone development by Jeff Lamarche. Jeff is the author of the best beginners book for iPhone dev “Beginning iPhone development”. Recently I found his profile at LinkedIn, and found he was a law school graduate, which is total surprise to me. He is definitely not a lawyer type in terms of writing (blog) and talking style (from his tweets).

Cocoanetics (aka Dr. Touch): Oliver Drobnik, the former Windows Admin turned full time iPhone iOS developer lives in Austria (Europe). Note he recently changed the name from Dr. Touch to Cocoanetics. Regardless the name change, I found he has a very good sense of both technology and business: I think his article on Notifications and “Part Store” (he sold his components software like parts) are very interesting.

iPhone developer:tips written primarily by John Muchow, who is the author of Core J2ME (which is the primary mobile development language pre iPhone, it is still used on Blackberry platform, and note Android used a different Java virtual machine developed by Google). I think some article such as “rename Xcode project”, “Prevent application being placed in background” etc. to be interesting.

iPhone development blog: written by Nick Dalton who got into iPhone dev early. A lot of goodies include this iPhone iOS app store reject reasons. I believe he is a co-founder and CTO of a mobile development firm in SF (can not recall the company name on top of my head, you may google).

Ray Wenderlich: the blog bears the author’s name. It has a lot of meaningful tutorials (not those “Hello world” stuff). Besides that, I found this How to host beta test for iOS app” to be interesting.

Other Resources, news, gossips etc
iPhone developer news (Apple): get it from Apple iOS developer center. The official place for all the announcement etc.

Mobile Orchard: used to be good technical stuff, stopped update this April, just resumed blogging.

43 iPhone app development resources: the list is a bit dated, but still useful.

I will add more as time goes.

Categories
iPhone app

Submit my 1st iPhone iOS app, wait for review

Reading Time: < 1 minute

After I initially upload myNestEgg (Aug 30 night), I did couple “developer reject” to add data persistence (Aug 31), and correct icon matching problem (Sept 7). It’s still in the “Wait for review” as of this writing.

Interestingly today Apple announced some change of iOS app license agreement, and put up a new App Store Review guidelines. One needs the iOS developer program to read the full content. But one can always read that from google news (I personally like what arstechnica has to say).

BTW, I found this Apple iOS App Store submission tips to be helpful. And this thread How long “waiting for review” to be fun. Per this thread, I should start working on the next app. Or start port my app to Android?