[ iOS ]建立連線並更新progress bar

連線下載進度條

何時使用callback 


何時使用Delegate 


連線code

1. .h繼承檔案

2 code
@interface ViewController : UIViewController 
<NSURLSessionDataDelegate, NSURLSessionDelegate>, NSURLSessionTaskDelegate>

-(void)getData{
    //建立連線
    -(void)getData{
    NSString *urlStr = @"http://international.download.nvidia.com/geforce-com/international/images/assassins-creed-iv-black-flag/assassins-creed-iv-black-flag-pc-screenshot-01.png";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    NSURLSessionConfiguration *conf = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:conf delegate:self delegateQueue:[NSOperationQueue new]];
    
    NSURLSessionDataTask *dt = [session dataTaskWithURL:url];
    
    
    [dt resume];
}
// 每次回傳一部分資料
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    
    //NSLog(@"%@", response);
    
    fileSize = [response expectedContentLength];
    
    completionHandler(NSURLSessionResponseAllow);
    
}
//回傳標頭檔 並處理檔案累加  計算progress bar 百分比
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    //NSLog(@"TEST");
    
    [fileData appendData:data];
    
    long long currentSize = [fileData length];
    
    //NSLog(@"%f", currentSize*1.0/fileSize);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        progess.progress = currentSize*1.0/fileSize;
    });
    
    
}
//完成後執行 
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    if (!error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            imgv.image = [[UIImage alloc] initWithData:fileData];
        });
        
    } else {
        // 處理錯誤
    }
}

留言