通過代理實現網絡請求@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.創建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.設置代理,發送請求(三種實現的方式、根據實際開發需求選擇)
//3.1
//[NSURLConnection connectionWithRequest:request delegate:self];
//3.2
//[[NSURLConnection alloc]initWithRequest:request delegate:self];
//3.3 設置代理,時候發送請求需要檢查startImmediately的值
//(startImmediately == YES 會發送 | startImmediately == NO 則需要調用start方法)
NSURLConnection * connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//調用開始方法
[connect start];
// [connect cancel];//取消
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
//1.當接收到服務器響應的時候調用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%s",__func__);
}
//2.接收到服務器返回數據的時候調用,調用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s",__func__);
//拼接數據
[self.resultData appendData:data];
}
//3.當請求失敗的時候調用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%s",__func__);
}
//4.請求結束的時候調用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__func__);
NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}