从网址下载文件并保存到iPhone上的资源 [英] Downloading a file from url and saving to resources on iPhone

查看:121
本文介绍了从网址下载文件并保存到iPhone上的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过编程方式从互联网下载文件(即sqlite数据库文件)到您的iPhone应用程序中,以供以后在应用程序中使用吗?

Is it possible to download a file (i.e. an sqlite database file) from the Internet into your iPhone application programmatically for later use within the application?

使用 NSURLConnection ,但无法保存文件。

I am trying using NSURLConnection, but not able to save the file.

这是我尝试的示例代码: p>

Here is the example code I am trying:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *file = [NSString stringWithFormat:@"http://en.wikipedia.org/wiki/Text_file"];
    NSURL *fileURL = [NSURL URLWithString:file];

    NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];  
}

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

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    NSLog(@"%@", [dirArray objectAtIndex:0]);

    NSString *path = [NSString stringWithFormat:@"%@/blah.text", [dirArray objectAtIndex:0]];

    if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
        NSLog(@"writeToFile error");
    }
    else {
        NSLog(@"Written!");
    }
}


推荐答案

是fileData?如何定义和初始化?

What is fileData? How is it defined and initialized?

  fileData = [NSMutableData data];

应该在之后:

NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];

您必须初始化fileData并根据内存管理规则保留它。

You have to initialize fileData and retain it per memory management rules.

尝试一下我的答案。它工作!

Try it with my answer. It Works!

这篇关于从网址下载文件并保存到iPhone上的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆