NSUrlconnection问题从一些文件主机接收数据

时间:2011-01-08 22:50:25

标签: iphone objective-c iphone-sdk-3.0

我正在尝试开发一个下载管理器。我现在可以从linkclick上的几乎任何地方下载文件。

在 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)请求navigationType:(UIWebViewNavigationType)navigationType 我检查url是否是一个像zipfile这样的二进制文件的url。比我设置nsurlconnection


    NSMutableURLRequest  *urlRequest = [NSMutableURLRequest requestWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 
                                                               timeoutInterval:20.0];
        [urlRequest setValue:@"User-Agent" forHTTPHeaderField:@"Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/418.9 (KHTML, like Gecko) Safari/419.3"];
        NSURLConnection *mainConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
        if (nil == mainConnection) {
            NSLog(@"Could not create the NSURLConnection object");
        }   

  • (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse)response { self.tabBarController.selectedIndex=1; [receivedData setLength:0]; percent = 0; localFilename = [[[url2 absoluteString] lastPathComponent] copy]; NSLog(localFilename);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0] ;
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:localFilename];
    [[NSFileManager defaultManager] createFileAtPath:appFile contents:nil attributes:nil]; [downloadname setHidden:NO]; [downloadname setText:localFilename]; expectedBytes = [response expectedContentLength]; exp = [response expectedContentLength]; NSLog(@"content-length: %lli Bytes", expectedBytes); file = [[NSFileHandle fileHandleForUpdatingAtPath:appFile] retain]; if (file) {

    [file seekToEndOfFile];
    

    } }

  • (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if (file) { [file seekToEndOfFile]; } [file writeData:data]; [receivedData appendData:data]; long long resourceLength = [receivedData length];
    float res = [receivedData length]; percent = res/exp; [progress setHidden:NO]; [progress setProgress:percent]; NSLog(@"Remaining: %lli KB", (expectedBytes-resourceLength)/1024); [kbleft setHidden:NO]; [kbleft setText:[NSString stringWithFormat:@"%lli / %lli KB", expectedBytes/1024 ,(resourceLength)/1024]]; }

在connectiondidfinish加载中我关闭文件。除了像filedude.com之前有捕获程序的主机之外,几乎每个主机都能正常工作 在uiwebview我可以浏览下载页面进入验证码并获取下载链接。当我点击它时,文件将在文件目录中创建,文件名和下载开始,但他没有得到任何数据。每个文件都有0kb和NSLog(@“content-length:%lli Bytes”,expectedBytes);给出类似100-400字节的东西。

有人可以帮我解决这个问题吗?

亲切的问候

3 个答案:

答案 0 :(得分:0)

应检查响应是什么

NSLog(@"%@", [connection allHttpHeaderFields])

答案 1 :(得分:0)

查看 ASIHttpRequest

http://allseeing-i.com/ASIHTTPRequest/

非常灵活可靠。只有你有真正独特的要求,最好自己编写。

答案 2 :(得分:0)

您是否可能没有关注HTTP重定向?您是否尝试过捕获并查看实际收到的数据?