NSURLConnection 不响应Delegate方法

关于这个问题头疼了很长时间,明明已经写了:

self.connection = [[NSURLConnection alloc] initWithRequest:requestLoad delegate:self];
connection的delegate代理为self,但是就是不执行其对应的Delegate方法,很少郁闷

解决方法就是为这个线程开启一个runloop使它始终处于运行状态,需要定一个全局的BOOL类型的finished变量来进行控制。代码如下:

 //设置请求超时时间为30s
            NSMutableURLRequest *requestLoad = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://box.zhangmen.baidu.com/bdlrc/93/9351.lrc"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
            
            self.connection = [[NSURLConnection alloc] initWithRequest:requestLoad delegate:self];
            //开启一个runloop,使它始终处于运行状态
            
            UIApplication *app = [UIApplication sharedApplication];
            app.networkActivityIndicatorVisible = YES;
            finished = NO;
            while (!finished)
            {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
            


总算给解决了。

之后,就会调用NSURLConnection的下面的代理方法了:

#pragma mark - NSURLConnection Delegate Methods
//接受完http协议头,开始真正结束数据时调用此方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(self.loadData == nil)
        self.loadData = [[NSMutableData alloc] initWithCapacity:2048];
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    NSInteger statusCode = [res statusCode];
    if(statusCode >= 400)
    {
        NSLog(@"HTTP ERROR CODE%d",statusCode);
    }
    NSDictionary *dic = [res allHeaderFields];
    NSLog(@"all Header Field %@",dic);
    
    NSLog(@"response");
}

//网络请求时,每接受一段数据就会调用此函数方法
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if(self.loadData == nil)
        self.loadData = [[NSMutableData alloc] initWithCapacity:2048];
    [self.loadData appendData:data];
}

//下载完成,可以对一些数据进行处理,将文件保存到沙盒中
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.loadData writeToFile:self.fileName atomically:YES];
    NSLog(@"%@下载完成",self.fileName);
    
    finished = YES;
    self.connection = nil;
    
    UIApplication *app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = NO;
}

//请求失败时调用此方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"load error:%@",[error description]);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接失败" message:@"网络请求超时" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
    [alert release];
    
    UIApplication *app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = NO;
}

大功告成!!!

你可能感兴趣的:(Object-C编程语言,IOS开发)