从URL下载文件并保存到iPhone上的资源

时间:2010-01-20 15:01:01

标签: ios cocoa-touch nsurlconnection

是否可以通过程序方式将文件(即sqlite数据库文件)从Internet下载到您的iPhone应用程序中,以便以后在应用程序中使用?

我正在尝试使用NSURLConnection,但无法保存文件。

以下是我正在尝试的示例代码:

- (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!");
    }
}

4 个答案:

答案 0 :(得分:5)

什么是fileData?它是如何定义和初始化的?

  fileData = [NSMutableData data];

应该在以下某处:

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

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

尝试我的回答。它有效!

答案 1 :(得分:4)

您需要使用stringByAppendingPathComponent

扩展路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];

答案 2 :(得分:4)

在方法中尝试此代码并执行,

NSURL *url=[NSURL URLWithString:@"http://en.wikipedia.org/wiki"];

NSData *dbFile = [[NSData alloc] initWithContentsOfURL:url];   

NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"Documents"]];

NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Text_file.txt"];  

[dbFile writeToFile:filePath atomically:YES];

答案 3 :(得分:0)

这对你有用。

NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL  *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
  NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString  *documentsDirectory = [paths objectAtIndex:0];  

  NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
  [urlData writeToFile:filePath automically:YES];
}

请注意,writeToFile方法是同步的,因此它会暂停/阻止您的用户界面。