NSURLConnection進捗画像ダウンロード

3245 ワード

ステップ1:2つのプロトコルを継承

     1
- (void)connection:connection didFailWithError:error;//    
- (BOOL)connectionShouldUseCredentialStorage:connection;//        

     2
- (void)connection:connection didReceiveResponse:response;//    
- (void)connection:connection didReceiveData:data;//        
- (void)connection:connection didFailWithError:error;//    
- (void)connectionDidFinishLoading:connection;//    


ステップ2:4つのプロパティを作成する
@property (nona, ) UIProgressView *progessView;//   
@property (nona, ) UILabel *progessLabel;//       
@property (nona, ) NSMutableData *downloadData;//       
@property (nona, ) long long allSizeBytes; //     

ステップ3:リクエストの送信、ダウンロードの開始
/*
 *  :    ,  url      
 *
 *
 */
- (void)startDownloadWithUrl:(NSURL *)url
{
    //1.      
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    //2.      
    [NSURLConnection connectionWithRequest:request delegate:self]; 
    [self initProgessView]; //     
    [self initProgessLabel]; //         
}

プロキシメソッド
ステップ4:サーバ応答の受信
#pragma mark - NSURLConnectionDelegate    
/**
 *           
 */
- (void)connection:(NSURLConnection *)connection 
didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"       ");
    //    
    self.downloadData.length = 0;
    //       
    self.allSizeBytes = response.expectedContentLength;
    //1.    
    NSString *filename = response.suggestedFilename;
    NSLog(@"    :%@",filename);
    //2.     
    long long fs = response.expectedContentLength;
    NSLog(@"     :%0.01f MB",fs/1024.0/1024.0);
    //3.    
    NSString *type = response.MIMEType;
    NSLog(@"    :%@",type);
    //4.   
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSInteger statusCode = httpResponse.statusCode;
    NSLog(@"   :%ld",statusCode);
    //5.        
    NSDictionary *dic = httpResponse.allHeaderFields;
    NSLog(@"   :%@",dic);
}

ステップ5:サーバデータの受信(バイナリデータデータ、一点)
/**
 *          ,         ,              。
 *                    ,      
 */
- (void)connection:(NSURLConnection *)connection
 didReceiveData:(NSData *)data
{
    //    
    [self.downloadData appendData:data];
    //    
    CGFloat progess = (CGFloat)self.downloadData.length /
 self.allSizeBytes;
    //     
    self.progessView.progress = progess;
    //    %   %%
    self.progessLabel.text = 
[NSString stringWithFormat:@"%0.1f%%",progess * 100];
}

ステップ6:サーバデータの受信が完了しました(この方法に成功しました)
/**
 *        
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //1.    
    [self.progessLabel removeFromSuperview];
    [self.progessView removeFromSuperview];
    //2.    
    self.image = [UIImage imageWithData:self.downloadData];
}

ステップ6:サーバデータの受信に失敗しました(このメソッドに失敗しました)
/**
 *      ,        
 */
- (void)connection:(NSURLConnection *)connection
 didFailWithError:(NSError *)error
{
    NSLog(@"    %@",error);
}

マイクロクラウドディスクの進捗状況付き画像ダウンロードdemo