ios - 从url下载文件并保存到iPhone上的资源

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

最佳答案

什么是文件数据?它是如何定义和初始化的?

  fileData = [NSMutableData data];

应该在某处之后:

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

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

试试看我的回答。有用!

关于ios - 从url下载文件并保存到iPhone上的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2102267/

相关文章:

ios - UIButton 之外的 TouchUpInside 边界

objective-c - 使用中世纪(小写,无衬里)数字

iphone - tableview 删除部分中的最后一行

ios - 将 TLS V1.1/V 1.2 与 NSURLConnection 结合使用

ios - 网络 iOS : Background/MainThread?

nsurlconnection - 可变 NSHTTPURLResponse 或 NSURLResponse

ios - Apple 开发者帐户 - 共享凭据

ios - 我的应用程序正在请求 “Have offline access” 的权限,为什么?

ios - rightBarButtonItem,leftBarButtonItem 问题

iphone - 在 Mac/iPhone 上进行联网的最有效方法?