Network requests in iOS development
Today, I'll talk about network requests during iOS development.
About the importance of network requests I don't think I need to say more. For mobile clients, the importance of the network is self-evident. Common network requests have synchronous get, synchronous post, asynchronous get, asynchronous post. Today, let's look at four ways to implement network requests.
One, synchronous get
| 123456789101112 |
// 1.将网址初始化成一个OC字符串对象NSString *urlStr = [NSString stringWithFormat:@"%@?query=%@®ion=%@&output=json&ak=6E823f587c95f0148c19993539b99295", kBusinessInfoURL, @"银行", @"济南"];// 如果网址中存在中文,进行URLEncodeNSString *newUrlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];// 2.构建网络URL对象, NSURLNSURL *url = [NSURL URLWithString:newUrlStr];// 3.创建网络请求NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];// 创建同步链接NSURLResponse *response = nil;NSError *error = nil;NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; |
When you create a sync link, you can parse it in a corresponding way. The same is true for creating asynchronous connections below.
Second, synchronous post
| 1234567891011121314151617 |
// 1.根据网址初始化OC字符串对象 NSString *urlStr = [NSString stringWithFormat:@"%@", kVideoURL]; // 2.创建NSURL对象 NSURL *url = [NSURL URLWithString:urlStr]; // 3.创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 4.创建参数字符串对象 NSString *parmStr = @"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"; // 5.将字符串转为NSData对象 NSData *pramData = [parmStr dataUsingEncoding:NSUTF8StringEncoding]; // 6.设置请求体 [request setHTTPBody:pramData]; // 7.设置请求方式 [request setHTTPMethod:@"POST"]; // 创建同步链接 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; |
Three, asynchronous get
| 1234567891011 |
NSString *urlStr = [NSString stringWithFormat:@"http://image.zcool.com.cn/56/13/1308200901454.jpg"]; NSString *newStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:newStr]; NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; //异步链接(形式1,较少用) [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { self.imageView.image = [UIImage imageWithData:data]; // 解析 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@", dic); }]; |
Iv. Asynchronous Post
| 1234567891011121314 |
// POST请求 NSString *urlString = [NSString stringWithFormat:@"%@",kVideoURL]; //创建url对象 NSURL *url = [NSURL URLWithString:urlString]; //创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10]; //创建参数字符串对象 NSString *parmStr = [NSString stringWithFormat:@"method=album.channel.get&appKey=myKey&format=json&channel=t&pageNo=1&pageSize=10"]; //将字符串转换为NSData对象 NSData *data = [parmStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; [request setHTTPMethod:@"POST"]; //创建异步连接(形式二) [NSURLConnection connectionWithRequest:request delegate:self]; |
In general, when you create an asynchronous connection, the first method is seldom used, and the proxy method is often used. On nsurlconnectiondatadelegate, we often use the Protocol method for a few:
| 1234567891011121314151617 |
// 服务器接收到请求时- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{}// 当收到服务器返回的数据时触发, 返回的可能是资源片段- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{}// 当服务器返回所有数据时触发, 数据返回完毕- (void)connectionDidFinishLoading:(NSURLConnection *)connection{}// 请求数据失败时触发- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%s", __FUNCTION__);} |
Finally, analyze the differences between these kinds of network requests.
The difference between a GET request and a POST request:
1. The interface of the GET request contains the parameters section, and the parameters are passed as part of the URL and between the server address and the parameter. to the interval. The POST request separates the server address from the parameter, only the server address in the request interface, and the parameter is submitted to the backend server as part of the request.
2. The GET request parameters appear in the interface and are not secure. The POST request is relatively secure.
3. Although both get requests and post requests can be used to request and submit data, general get is used to request data from the background, and post is used to submit data to the background.
The difference between synchronous and asynchronous:
Synchronous Link: The main thread to request data, when the data request is complete, other threads are not responding, will cause the program on the phenomenon of suspended animation.
Asynchronous Link: will open a separate thread to handle the network request, the main thread is still in an interactive state, the program runs smoothly.
How IOS network requests