带有NSURLConnection的MBProgressHUD

问题描述 投票:3回答:3

我正在尝试将MBProgressHUD与NSURLConnection一起使用。

[MBProgressHUD报告的演示项目中的示例:

- (IBAction)showURL:(id)sender {
    NSURL *URL = [NSURL URLWithString:@"https://github.com/matej/MBProgressHUD/zipball/master"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
    [connection release];

    HUD = [[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] retain];
    HUD.delegate = self;
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    expectedLength = [response expectedContentLength];
    currentLength = 0;
    HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    currentLength += [data length];
    HUD.progress = currentLength / (float)expectedLength;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    HUD.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
    HUD.mode = MBProgressHUDModeCustomView;
    [HUD hide:YES afterDelay:2];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [HUD hide:YES];
}

[运行它,HUD在确定模式下旋转良好。

我试图实现这一点,但是在这里

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        currentLength += [data length];
        HUD.progress = currentLength / (float)expectedLength;
    }

圆圈为空且未填充。

我不知道这是否取决于请求的URL的尺寸。

我请求从我的网站下载plist(〜80 kb),但圈子一直空白,控制台报告

<Error>: void CGPathAddArc(CGPath*, const CGAffineTransform*, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat, bool): invalid value for start or end angle.

我什至试图这样做:

float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        HUD.progress = progress;
    }

但是现在圆圈已完全充满,没有进行任何动画处理。

我认为这取决于请求的URL的尺寸,但是我不太确定,有人知道如何解决此问题吗?

objective-c nsurlconnection mbprogresshud
3个回答
7
投票

我用这种方法解决了这个问题,从NSURLRequest切换到NSMutableURLRequest并将值none设置为编码(以前在gzip中使用)

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:anURL];
[request addValue:@"" forHTTPHeaderField:@"Accept-Encoding"];

6
投票

您应该检查[response expectedContentLength]中的didReceiveResponse的值。

http服务器可以省略“ Content-Length”标头,而使用“ Transfer-Encoding:chunked”。在那种情况下,内容长度是先验未知的,[response expectedContentLength]返回NSURLResponseUnknownLength(即-1)。]

我可以想象将HUD.progress设置为负值会导致CGPathAddArc控制台消息。

根据文档,还可能发生累积的currentLength大于预期的响应长度,因此您也应该检查该长度。


0
投票

我迅速通过在url请求的Accept-Encoding

© www.soinside.com 2019 - 2024. All rights reserved.