Sunday, January 25, 2015

iOS Tutorial - Part 27 - HttpRequest POST, GET (NSURLConnection) II

HttpRequest POST, GET (NSURLConnection) II


Video Description 
This is the second part of NSURLConnection tutorial. If you have not read or watched the first part, click here to watch it first. In this part we will learn how to create a GET and POST request.

How to create GET request

The following method will do the GET request
- (void)httpGetRequest
{
    NSString *str = @"http://content.guardianapis.com/search?api-key=test";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:GET];
    self.restApi.delegate = self;
    [self.restApi httpRequest:request];
}
In the first line we add the url address that we want to send the GET request. In the second line we convert the special characters of the url in first line. In the third like we convert the str into URL type that Objective-C can read it as an URL. In the fourth line we create our actual request with the URL we created. In the fifth line we specify the Http type (Here it's GET). The sixth line we are setting restApi delegate equal to self to implement RestApi class. In the last line we call RestAPI class to send our request (RestApi is created in previous session).

How to create POST request

- (void)httpPostRequest
{
    NSString *postBody = @"api-key=test";
    NSString *str = @"http://content.guardianapis.com/search";
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:POST];
    [request setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
    self.restApi.delegate = self;
    [self.restApi httpRequest:request];
}
It's exactly like sending GET request, the only difference is that it has 2 more lines. The first line and the seventh line. In the first line specifies the post body, which may includes post parameters. In the seventh line we attach the post body to the request.

What to do next

Click here for the third part of Http Request

Sunday, January 18, 2015

iOS Tutorial - Part 26 - HttpRequest POST, GET (NSURLConnection) I

HttpRequest POST, GET (NSURLConnection) I


Video Description 
One of the most popular functionality that many apps have is being able to send and receive data over internet. As you may know this service is called Http Request. The type of request could be POST, GET, DELETE, ... . Once you understand one type of request, you can use for other types of requests. Just to simplify the subject, it's divided into multiple sessions. In this session we talk about an API for Http Request, which is NSURLConnection.

RestAPI

I have created a class called "RestAPI". This class is designed to implement NSURLConnection delegate methods. Delegate methods that we are going to implement in this class are as follow:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receivedData appendData:data];
}
This method appends the response data that is received from server or web. You may ask why we should append the data, It'd because most of the time server or web divides into separate parcels and sends it one by one. It's our job to append this data into a single object. We store the data in self.receivedData property. This property has a type called "NSMutableData". we define this property like bellow:
@property (nonatomic, strong) NSMutableData *receivedData;
We initialize it in it's setter like bellow:
- (NSMutableData *)receivedData
{
    if (!_receivedData)
    {
        _receivedData = [[NSMutableData alloc] init];
    }
    return _receivedData;
}
The next NSURLConnection delegate method is:
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@", error.description);
}
If any error happens during the request, this method will be called. In this tutorial for the sake of simplicity we won't handle network errors, we just log the error in console and nothing else but you may handle the error properly. The other important delegate method is as follow:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.delegate getReceivedData:self.receivedData sender:self];
    self.delegate = nil;
    self.requestConnection = nil;
    self.receivedData = nil;
}
When the response for our request becomes available this method will be called. After we are done with the response that we get, we put everything to nil because we may want to use them again through the application and they should be initialized again. The first line of the implementation of this method is calling a delegate method of "RestAPIDelegate", which is in RestAPI.h. In Session 18 (Create Protocol (Delegate), prepareForSegue) we have learnt how to create a protocol and what are they good for. In RestAPI.h file we have created a delegate method in order to be notified whenever the response becomes ready. This delegate has one method which is used in connectionDidFinishLoading.
@class RestAPI;
@protocol RestAPIDelegate
- (void)getReceivedData:(NSMutableData *)data sender:(RestAPI *)sender;
@end
Lastly we have a public method in RestAPI.h which is
- (void)httpRequest:(NSMutableURLRequest *)request;
Each class that wants to do Http Request should call this method by passing request argument. In next session we will talk how to create this request.


What to do next

Click here for the second part of Http Request