Set progress bar for downloading NSData

前端 未结 3 513
失恋的感觉
失恋的感觉 2021-02-09 14:21
NSURL *url = [NSURL URLWithString:@\"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173\"]; 
NSData *data = [NSData dataWithContentsOfURL:url]         


        
3条回答
  •  攒了一身酷
    2021-02-09 15:12

    To give a more detailed example:

    in your .h file do

    @interface YourClass : YourSuperclass
    

    in your .m file do

    @property (nonatomic) NSMutableData *imageData;
    @property (nonatomic) NSUInteger totalBytes;
    @property (nonatomic) NSUInteger receivedBytes;
    

    And somewhere call

    NSURL *url = [NSURL URLWithString:@"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    

    And also implement the delegate methods

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
        NSDictionary *dict = httpResponse.allHeaderFields;
        NSString *lengthString = [dict valueForKey:@"Content-Length"];
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        NSNumber *length = [formatter numberFromString:lengthString];
        self.totalBytes = length.unsignedIntegerValue;
    
        self.imageData = [[NSMutableData alloc] initWithCapacity:self.totalBytes];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [self.imageData appendData:data];
        self.receivedBytes += data.length;
    
        // Actual progress is self.receivedBytes / self.totalBytes
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        imageView.image = [UIImage imageWithData:self.imageData];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
        //handle error
    }
    

提交回复
热议问题