iOS网络请求 NSURLConnection

URLConnection的几种用法

1
2
3
4
5
6
/*
触发
*/
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self async];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**

Get请求-同步

*/
- (void) sync{
NSURL* url = [NSURL URLWithString:@"https://tianqiapi.com/api?version=v1&appid=53827541&appsecret=sIY6i0fQ"];

NSURLRequest *request = [[NSURLRequest alloc]initWithURL: url];

NSHTTPURLResponse * response = **nil**;

NSData *data = [NSURLConnection sendSynchronousRequest:request

returningResponse: &response

error: **nil**];

NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

NSLog(@"%zd",response.statusCode);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**

Get请求-同步

*/

- (void)async{

NSURL* url = [NSURL URLWithString:@"https://tianqiapi.com/api?version=v1&appid=53827541&appsecret=sIY6i0fQ"];

NSURLRequest *request = [[NSURLRequest alloc]initWithURL: url];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * *connectionError) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
result = [self stringByReplaceUnicode:result];
NSLog(@"%@",result);
NSHTTPURLResponse* res = (NSHTTPURLResponse*)response;
NSLog(@"%zd",res.statusCode);

}];

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
Get请求-代理
*/
//实现协议 <NSURLConnectionDataDelegate>

- (void)delegate{

NSURL* url = [NSURL URLWithString:@"https://tianqiapi.com/api?version=v1&appid=53827541&appsecret=sIY6i0fQ"];

NSURLRequest *request = [[NSURLRequest alloc]initWithURL: url];

[NSURLConnection connectionWithRequest:request delegate:self];

}
/*
协议对应的方法
*/
#pragma mark -NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"%s",__func__);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"%s",__func__);
[self.resultData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%s",__func__);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"%s",__func__);
NSLog(@"%@",[[NSString alloc]initWithData:_resultData encoding:NSUTF8StringEncoding]);

}