我是iPhone开发人员的新手,
如何从url
下载epub文件并将其存储在资源文件夹中?
这是我的代码段,
- (void)viewDidLoad
{
[super viewDidLoad];
fileData = [NSMutableData data];
NSString *file = [NSString stringWithFormat:@"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
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];
}
- (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:@"%@", [dirArray objectAtIndex:0]];
if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(@"writeToFile error");
}
else {
NSLog(@"Written!");
}
}
我无法在NSLog
中看到任何内容。
答案 0 :(得分:1)
写入时也会出现创建文件路径的问题。您没有在路径中指定任何文件名。在下面的行中,我使用了文件名“filename.txt”。给一些正确的名称,它会写。
NSString *path = [NSString stringWithFormat:@"%@/filename.txt", [dirArray objectAtIndex:0]];
创建网址时也存在问题。这样做,
NSString *file = [NSString stringWithString:@"http://www.google.co.in/url?sa=t&rct=j&q=sample%20epub%20filetype%3Aepub&source=web&cd=2&ved=0CFMQFjAB&url=http%3A%2F%2Fdl.dropbox.com%2Fu%2F1177388%2Fflagship_july_4_2010_flying_island_press.epub&ei=i5gHUIOWJI3RrQeGro3YAg&usg=AFQjCNFPKsV-tieF4vKv7BXYmS-QEvd7Uw"];
NSURL *fileURL = [NSURL URLWithString:file];
您已使用以下行创建了文件数据。
fileData = [NSMutableData data];
如下所示,
fileData = [[NSMutableData alloc]init];
OR
self.fileData = [NSMutableData data];
此处iOS会在您的连接委托被调用之前发布filedata。