nst / STHTTPRequest

Obj-C / Cocoa HTTP requests for humans
BSD 3-Clause "New" or "Revised" License
826 stars 75 forks source link

STHTTPRequest2 : In downloadProgressBlock it doesnot have totalBytesExpectedToReceive value #34

Closed paresh-navadiya closed 9 years ago

paresh-navadiya commented 9 years ago

Thanks for library :+1:

Sample code where i face issue is given below :

STHTTPRequest *request = [STHTTPRequest requestWithURLString:@"http://a1408.g.akamai.net/5/1408/1388/2005110403/1a1a1ad948be278cff2d96046ad90768d848b41947aa1986/sample_iTunes.mov.zip"];

request.completionDataBlock = ^(NSDictionary *headers, NSData *downloadedData)
{
    // Completion Block
    if (downloadedData)
    {
        NSLog(@"downloaded");
    }
};

request.downloadProgressBlock = ^(NSData *dataJustReceived, int64_t totalBytesReceived, int64_t totalBytesExpectedToReceive)
{
    // notify user of download progress
    // use the stream
    NSLog(@"%lld / %lld",totalBytesReceived,totalBytesExpectedToReceive);
    NSLog(@"Progress : %f",(float)totalBytesReceived/(float)totalBytesExpectedToReceive);
};

request.errorBlock = ^(NSError *error) {
    // error
    NSLog(@"%@",[error description]);
};

[request startAsynchronous];
paresh-navadiya commented 9 years ago

I changed below method and it worked :

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {

 __weak typeof(self) weakSelf = self;

dispatch_async(dispatch_get_main_queue(), ^{

    __strong typeof(weakSelf) strongSelf = weakSelf;
    if(strongSelf == nil) return;

    if([dataTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *r = (NSHTTPURLResponse *)[dataTask response];

        if (r)
        {
            strongSelf.responseHeaders = [r allHeaderFields];
            strongSelf.responseStatus = [r statusCode];
            strongSelf.responseStringEncodingName = [r textEncodingName];
            strongSelf.responseExpectedContentLength = [r expectedContentLength];

            NSArray *responseCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:strongSelf.responseHeaders forURL:dataTask.currentRequest.URL];
            for(NSHTTPCookie *cookie in responseCookies) {
                //NSLog(@"-- %@", cookie);
                [strongSelf addCookie:cookie]; // won't store anything when STHTTPRequestCookiesStorageNoStorage
            }
        }
        else {
            NSDictionary *userInfo = @{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"bad response class: %@", [dataTask.response class]]};
            NSError *e = [NSError errorWithDomain:NSStringFromClass([strongSelf class]) code:0 userInfo:userInfo];
            strongSelf.errorBlock(e);
            [session finishTasksAndInvalidate];
            return;
        }

    }

    completionHandler(NSURLSessionResponseAllow);

 });
}