【问题标题】:NSMutableData Save to a FileNSMutableData 保存到文件
【发布时间】:2012-02-28 21:32:46
【问题描述】:

我使用下面显示的代码下载了文件。然后我试图将 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,并测试函数的返回值,那肯定会有所帮助。

标签: iphone xcode nsmutabledata


【解决方案1】:

您不能在应用程序包中编写代码。您需要将其保存在其他位置,例如应用的 Documents 目录:

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 文件夹。但是,使用命令行我能够找到这个保存的文件。感谢诺亚的意见。
猜你喜欢
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 2017-11-18
  • 2013-11-15
  • 1970-01-01
  • 2013-01-02
  • 2012-03-21
  • 1970-01-01
相关资源
最近更新 更多