【问题标题】:Download file to app directory in iphone将文件下载到iphone中的应用程序目录
【发布时间】:2012-08-18 16:45:42
【问题描述】:

我是 iPhone 新手,

我目前正在开发一个 iPhone 应用程序,并希望实现从 Internet 下载文件的功能。我已经创建了UIWebView,但想知道在 webview 中链接到文件时捕获文件的最佳方法,然后将它们下载到文档目录中的指定文件夹。

这是我的代码 sn-p,

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ 
    [self.fileData setLength:0];
}

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
 {
       [self.fileData appendData:data1]; 
 }

 - (void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
     [activityIndicator stopAnimating];
     activityIndicator.hidden=TRUE;
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    url = [request URL];

    //CAPTURE USER LINK-CLICK.
    NSString *file = [NSString stringWithString:[url absoluteString]];;
    NSURL *fileURL = [NSURL URLWithString:file];
    NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
    [NSURLConnection connectionWithRequest:req delegate:self];
     data = [NSData dataWithContentsOfURL:url];

            //Saving file at downloaded path.

        DirPath = [DestPath stringByAppendingPathComponent:[url lastPathComponent]];
        [data writeToFile:DirPath atomically:YES];

        UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
                                                                             message:nil delegate:nil 
                                                                   cancelButtonTitle:@"OK"
                                                                   otherButtonTitles:nil];
                        [Alert show];
                        [Alert release];



    return YES;   
}

问题是在哪里写条件,如果我的下载失败并且我的日志中显示警告:“wait_fences: failed to receive reply: 10004003”

【问题讨论】:

    标签: iphone ipad uiwebview nsdata writetofile


    【解决方案1】:

    您似乎在这段代码中多次执行相同的操作。例如,您创建一个新的 NSURLRequest 对象,即使已经在委托方法内部传递了一个对象?在创建新的 NSURLConnection 之后,您还运行同步 dataWithContentsOfURL 方法吗?您还将一些数据附加到属性中,只是对该属性不执行任何操作?

    您可能想要做的是在 UIWebView 应该加载时创建一个新的异步 NSURLConnection。从那里,允许 UIWebView 加载该页面。在您的委托方法内部,不是将数据附加到某个属性,而是将下载的数据附加到文件中。连接完成下载后,显示您的警报,通知用户数据已下载并保存。

    【讨论】:

    • 你知道任何示例教程吗?
    • 我给了你关于你需要做什么的明确指示。在大多数情况下,您已经在发布的代码中编写了它。
    猜你喜欢
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多