IOS network development: NSURLConnection

Source: Internet
Author: User

Today, I plan to summarize the network section in iOS development.

NSURLConnection is the easiest way to access the network, but has the least functions. Therefore, only simple network access is required;

Using NSURLConnection to access the network is roughly divided into four steps

Let's start the first three steps.

NSString * urlString = @ "http://m.baidu.com"; // If the URL contains Chinese, use the following sentence to convert it to unicode with a percent sign. // urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: urlString]; // you can create one by passing in only the url, but it is best to add a cache policy, and the timeout time is better. NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 2.0]; // The proxy here uses the controller, but it must comply with the <NSURLConnectionDataDelegate> protocol to process received data NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest: request delegate: self]; // start the connection. You can call another method in the previous line to start the connection when the connection is created. You can use another parameter constructor, however, it is best to manually start [connection start];

 

NSURLConnection class methods can also be directly started after the object is generated, but it is better to manually start it.

The above lines of code are preparations. Next we will write the proxy method.

# Pragma mark starts sending a request-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {_ data = [NSMutableData data];}

This method is called when a connection receives a response from the server to complete data receiving preparation.

I declare a member Variable _ data in the class extension to store the returned data. instantiate the data here or load it in the next method.

The next step is to receive data.

# Pragma mark received the returned data-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {// This should be a lazy load, if (nil = _ data) {_ data = [NSMutableData data];} [_ data appendData: data];}

It is worth noting that this method is called repeatedly. No matter how small the request is, the data may be called repeatedly. Therefore, a variable _ data member variable is required to splice the data.

Next, complete the loading.

# Pragma mark data Loading completed-(void) connectionDidFinishLoading :( NSURLConnection *) connection {NSString * str = [[NSString alloc] initWithData: _ data encoding: NSUTF8StringEncoding]; // baseurl is used to access website resources. It is too simple to write here. In fact, baseurl should dynamically obtain [_ webView loadHTMLString: str baseURL: [NSURL URLWithString: @ "http://m.baidu.com"]; _ data = nil ;}

This method will be called when the data transmission is complete to process the received data. Here, Because I access the Baidu page as an example, an html data is returned, convert it into a string and load it with a webView to display it. It can also be used to download data.

Next is the error handling page.

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

I only output an error here. You can restart the connection here.

In fact, in actual development, NSURLConnection is only suitable for handling some simple network connection work. When dealing with some complex protocols, it is quite painful. Generally, we are using the asi and afn frameworks, at the same time, it is exciting that Apple launched the NSURLSession in ios7. Well, I can only say that now all the networks in iOS can access the third-party framework and basically retire, I will update several posts about various network access frameworks recently, about afn and NSURLSession. as for asi .... although the framework of the author's sudden disappearance is very useful, it does not need to be used again.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.