1

我是 iPhone 开发者的新手,

如何从资源文件夹下载 epub 文件url并将其存储在资源文件夹中?

这是我的代码片段,

- (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.

4

1 回答 1

1

写入时创建文件路径也存在问题。您没有在路径中指定任何文件名。在下面的行中,我使用文件名作为“filename.txt”。给一些正确的名字,它会写。

NSString *path = [NSString stringWithFormat:@"%@/filename.txt", [dirArray objectAtIndex:0]];

创建 URL 也有问题。像这样做,

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];

或者

self.fileData = [NSMutableData data];

在这里,iOS 在调用连接委托之前释放文件数据。

于 2012-07-19T06:42:56.400 回答