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
}
4

1 回答 1

11

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

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"];
[data writeToFile:filePath atomically:YES];
于 2012-02-28T21:38:49.713 回答