iPhone Rss Reader App IOS Tutorial 2: HTTP Network Programming in IOS

On December 15, 2012, in iPhone iPad Object-C, by James Liu

To create a complete rss reader iphone app, http request and response are both necessary modules. Website, for example, WordPress powered website, usually provides rss feed feature. Hence, using our rss reader iphone app can easily get the rss feed contents from Http request. HTTP network programming in IOS is very simple. NSURLConnection class and related classes manage the common operations. If we want to download data to store in a file, we can use NSURLDownload, which will not used in our iphone rss reader app. In this tutorial, I will show you how to use NSURLConnection to send HTTP GET request and HTTP POST request.

This is the 2nd tutorial for iPhone Rss Reader app development, you can find all tutorials about this topics:

HTTP GET Connection

Http GET connection is the most simple task among the network programming. To start a “GET” network connection, we need to create following three available:

  • NSURL
  • NSURLRequest
  • NSURLConnection

Here is a piece of sample source code to show us how to start HTTP “GET” Request connection. It is almost an HTTP GET connection standard.

-(NSURLConnection *)getRSSContent:(NSString *)pageID rssurl:(NSString *)url delegate:(id<NSURLConnectionDataDelegate>)delegate
{
    NSURL *urlRef = [NSURL URLWithString:[url stringByAppendingString:pageID]];
    
    NSURLRequest *rssRequest = [NSURLRequest requestWithURL:urlRef];
    NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:rssRequest delegate:delegate startImmediately:YES];
    return connect;
}

In the Rss Reader App, we will read the rss from this site. To get the latest articles from this website, we request the following url:

http://jmsliu.com/feed?paged=1

“paged” is the pagination for Rss feed request. This type of url request is only available for WordPress powered website. Hence, to request a page of rss, we can invoke the function like below:

    RssHttpController *rssController = [[NewsController alloc] init];
    connection = [rssController getRSSContent:1 rssurl:@"http://jmsliu.com/feed?paged=" delegate:self];

HTTP POST Connection

HTTP POST connection is a little bit different from HTTP GET connection. Instead of NSURLRequest, we use NSMutableURLRequest for NSURLConnection and build the body data for the request. The following code is preparing the POST body.

#define POST_BODY_BOURDARY  @"boundary"

-(NSData *) createFormData:(NSDictionary *)loginData boundaryStr:(NSString *)bstr
{
    NSMutableData *result = [NSMutableData alloc];
    NSArray *keyArray = [loginData allKeys];
    for (int i=0; i < &#91;keyArray count&#93;; i++) { //ignore this comment >
        [result appendData: [[NSString stringWithFormat:@"--%@\n", bstr] dataUsingEncoding:NSUTF8StringEncoding]];
        [result appendData: [[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\n\n%@\n", [keyArray objectAtIndex:i],
                              [loginData valueForKey:[keyArray objectAtIndex:i]]]
                             dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    [result appendData: [[NSString stringWithFormat:@"--%@--\n", bstr] dataUsingEncoding:NSUTF8StringEncoding]];
    return result;
}

-(BOOL)getAccountStatus: (id<NSURLConnectionDataDelegate>)delegate
{
    //prepare the body content
    NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
    [dataDictionary setObject:@"post_value" forKey:@"postkey"];
    NSData *formData = [self createFormData:dataDictionary boundaryStr:POST_BODY_BOURDARY];
    
    NSURL *url = [NSURL URLWithString:ACCOUNT_STATUS_ADDRESS];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    //build the request body
    NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", POST_BODY_BOURDARY];
    [request setValue:contentTypeValue forHTTPHeaderField:@"Content-type"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:formData];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegate startImmediately:YES];
    if(connection)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

Http post request can also be used to upload file data from disk. We can use setHTTPBodyStream: to configure NSMutableURLRequest to read from an NSInputStream as the body content. This subject will be covered in another topic.

Get Http Response Data

When we create NSURLConnection, we should provide a delegate to listen the NSURLConnection response. The delegate shall implement the protocol NSURLConnectionDataDelegate. There are several protocol functions to be override in delegate class.

  • -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  • -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  • -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
  • -(void)connectionDidFinishLoading:(NSURLConnection *)connection

In didReceiveResponse, we initialize the data structure to receive the response data. In didReceiveData, we store the received data in data structure. After the response finished, connectionDidFinishLoading will be called. Here is the example:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receiveData = [NSMutableData data];
    [receiveData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receiveData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"RSS Error: %@", [error localizedDescription]);
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *result = [[NSString alloc] initWithData:receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", result);
}

iPhone Rss Reader App IOS Tutorial 3: XML Parser in IOS

The rss response are defined in xml format. In iPhone Rss Reader App IOS tutorial 3, I will show you how to use NSXMLParser to parser rss xml data into our data structure after receiving the rss feed data from website.

Tagged with:  

4 Responses to “iPhone Rss Reader App IOS Tutorial 2: HTTP Network Programming in IOS”

  1. tom says:

    Hi,
    Where I must set your code from tt2 in Xcode. I have downloaded your code from first tt (Version 1.0). But now….sorry I’m a rookie. Or have you a link to a new version? Can you help me?
    Many thanks
    Tom
    (sorry for my English)

  2. Pau says:

    Hi! This part has got me so confused. I’m making a table view controller app that gets its data from a google spreadsheet RSS feed. Will this step still be necessary? Cause I’ve seen some tutorials that don’t mention HTTP. Thanks so much for the help! 🙂

    • James says:

      Yes. This part is quite necessary, if you want to load RSS list from your website. I don’t know how you load your RSS from google spreadsheet. If it is a html page, then it will be a different story.

      Usually, RSS feed is a XML format. That’s why you need to load it to your app then parse it and show it in your format. HTTP loading cannot be omitted. If you didn’t find this part in other tutorials. I guess they just hide it or use some 3rd part library to make it not that important. My app is using the original Android code without any 3rd library.

      If you are not sure if your google spreadsheet , you can post your rss link and let me check if it is a standard RSS feed format.

      Best Regards

Leave a Reply

Free WordPress Themes

Weboy