Network requests in iOS development and network requests in iOS development

Source: Internet
Author: User

Network requests in iOS development and network requests in iOS development

Today, I opened a blog that I haven't written for a long time. I checked the date. It was just one month before I wrote my blog. This month, I learned a lot about iOS development, today we will talk about network requests during iOS development.

I don't need to talk about the importance of network requests. For mobile clients, the importance of the network is self-evident. Common network requests include synchronous GET, synchronous POST, asynchronous GET, and asynchronous POST. Today, let's take a look at the implementation methods of the four network requests.

1. Synchronize GET

// 1. initialize the URL into an OC String object NSString * urlStr = [NSString stringWithFormat: @ "% @? Query =%@ & region =%@ & output = json & ak = 6e823f587c95f0148c%3539b99295 ", kBusinessInfoURL, @" bank ", @" Jinan "]; // If the website contains Chinese characters, URLEncodeNSString * newUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; // 2. construct a network URL object, NSURLNSURL * url = [NSURL URLWithString: newUrlStr]; // 3. create a network request NSURLRequest * request = [NSURLRequest requestWithURL: url cachePolicy: hour timeoutInterval: 10]; // create a synchronization link NSURLResponse * response = nil; NSError * error = nil; NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: & error];

After the synchronization link is created, you can use the corresponding method for parsing. The same is true for creating an asynchronous connection.

Ii. synchronous POST

// 1. initialize the OC String object NSString * urlStr = [NSString stringWithFormat: @ "% @", kVideoURL]; // 2. create NSURL object NSURL * url = [NSURL URLWithString: urlStr]; // 3. create a request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // 4. create the parameter string object NSString * parmStr = @ "method = album. channel. get & appKey = myKey & format = json & channel = t & pageNo = 1 & pageSize = 10 "; // 5. convert the string to NSData object NSData * pramData = [parmStr dataUsingEncoding: NSUTF8StringEncoding]; // 6. set request body [request setHTTPBody: pramData]; // 7. set the request method [request setHTTPMethod: @ "POST"]; // create the synchronization link NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

3. asynchronous GET

NSString * urlStr = [NSString stringWithFormat: @ "http://image.zcool.com.cn/56/13/1308200901454.jpg"]; NSString * newStr = [urlStr encoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: newStr]; NSURLRequest * requst = [NSURLRequest requestWithURL: url cachePolicy: Required timeoutInterval: 10]; // asynchronous Link (Form 1, rarely used) [NSURLConnection sendAsynchronousRequest: requst queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError) {self. imageView. image = [UIImage imageWithData: data]; // parse NSDictionary * dic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil]; NSLog (@ "% @", dic) ;}];
Iv. asynchronous POST

// POST request NSString * urlString = [NSString stringWithFormat: @ "% @", kVideoURL]; // create a url object NSURL * url = [NSURL URLWithString: urlString]; // create a request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url cachePolicy: Required timeoutInterval: 10]; // create a parameter string object NSString * parmStr = [NSString stringWithFormat: @ "method = album. channel. get & appKey = myKey & format = json & channel = t & pageNo = 1 & pageSize = 10 "]; // converts a string to an NSData object NSData * data = [parmStr dataUsingEncoding: NSUTF8StringEncoding]; [request setHTTPBody: data]; [request setHTTPMethod: @ "POST"]; // create an asynchronous connection (Form 2) [NSURLConnection connectionWithRequest: request delegate: self];

Generally, the first method is rarely used when an asynchronous connection is created, and the proxy method is often used. For NSURLConnectionDataDelegate, we often use the following protocol methods:

// When the server receives the request-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {} // triggered when it receives the data returned by the server, the returned resource fragment may be-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {}// triggered when the server returns all data, the data is returned completely-(void) connectionDidFinishLoading :( NSURLConnection *) connection {} // triggered when the request data fails-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error {NSLog (@ "% s ", _ FUNCTION __);}

Finally, let's analyze the differences between these network requests.

Difference between GET request and POST request:

1. The GET request interface will include the parameter part. The parameter will be part of the URL? The post request separates the server address from the parameter. The request interface only contains the server address, and the parameter is used as part of the request and submitted to the backend server.

2. The GET request parameters will appear in the interface, which is not secure. The POST request is relatively secure.

3. Although both GET requests and POST requests can be used to request and submit data, generally GET requests are mostly used to request data from the background, and POST requests are mostly used to submit data to the background.

Differences between synchronous and asynchronous:

Synchronization link: the main thread requests data. When other threads do not respond before the data request is completed, the program will be suspended.

Asynchronous link: A separate thread is opened to process network requests. The main thread is still interactive and the program runs smoothly.






IOS Network Development

Mobile Phone: IOS has many network frameworks, the most classic ASHTTP
AFNETWORK is recommended.
Server: depending on the language you are familiar with, the server has a web service. Your client requests this web service and returns data. The data format is often json, xml, or string.

The other is the knowledge of uikit. Since you are a standalone app, this is not a problem.

In ios development, due to poor network performance, the interface frequently crashes and lags behind the loading interface. I use Asynchronous

The lag of the loading interface may be caused by blocking the main thread of the interface. Even if asynchronous requests are used, the number of requests should be minimized to compress the request data.

Related Article

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.