从网址下载文件并保存到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!