通過代理實現(xiàn)網(wǎng)絡(luò)請求@interface ViewController ()<NSURLConnectionDataDelegate>
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//1.確定請求路徑
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"];
//2.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.設(shè)置代理,發(fā)送請求(三種實現(xiàn)的方式、根據(jù)實際開發(fā)需求選擇)
//3.1
//[NSURLConnection connectionWithRequest:request delegate:self];
//3.2
//[[NSURLConnection alloc]initWithRequest:request delegate:self];
//3.3 設(shè)置代理,時候發(fā)送請求需要檢查startImmediately的值
//(startImmediately == YES 會發(fā)送 | startImmediately == NO 則需要調(diào)用start方法)
NSURLConnection * connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//調(diào)用開始方法
[connect start];
// [connect cancel];//取消
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
//1.當(dāng)接收到服務(wù)器響應(yīng)的時候調(diào)用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%s",__func__);
}
//2.接收到服務(wù)器返回數(shù)據(jù)的時候調(diào)用,調(diào)用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s",__func__);
//拼接數(shù)據(jù)
[self.resultData appendData:data];
}
//3.當(dāng)請求失敗的時候調(diào)用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%s",__func__);
}
//4.請求結(jié)束的時候調(diào)用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__func__);
NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}