是否可以通过编程方式从 Internet 将文件(即 sqlite 数据库文件)下载到您的 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!");
}
}