Calling restful POST PUT and DELETE methods in AFNetworking 2.0

Posted in :

stlplace
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];
    }
}

%d bloggers like this: