NSMutableData保存到文件

4

我使用下面的代码下载了文件。然后我试图将NSMutableData变量保存到文件中,但是文件没有被创建。我做错了什么?我需要将NSMutableData转换为NSString吗?

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response {
    response = [_response retain];
    if([response expectedContentLength] < 1) {
        data = [[NSMutableData alloc] init];
    }
    else {
        data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data {
    [data appendData:_data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];

    NSLog(@"saved: %@", filePath);
    [data writeToFile:filePath atomically:YES];
    NSLog(@"downloaded file: %@", data); //all i see in log is some encoded data here
}

如果你传递一个指向NSError变量的地址给writeToFile,并且测试函数的返回值,这肯定会有所帮助。 - Philip Sheard
1个回答

11

你不能在应用程序的包中进行写操作。你需要将它保存到其他地方,比如应用程序的文档目录:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
[data writeToFile:filePath atomically:YES];

谢谢,这个可行。文件保存在模拟器中的/USER/apple/Library/Application .../iPhone Simulator/5.0/App_key/Documents。我无法从文件浏览中找到Library文件夹。但是,使用命令行,我能够找到这个已保存的文件。感谢Noah的帮助。 - user914425

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接