iOS開發(fā)-NSURLConnection(通過代理方法發(fā)送GET請求)

通過代理實現(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]);
}



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容