iphone – NSMutableData保存到文件
发布时间:2020-12-14 18:10:41 所属栏目:百科 来源:网络整理
导读:我使用下面显示的代码下载文件.然后我试图将NSMutableData变量保存到文件,但是,不创建该文件.我究竟做错了什么?我需要将NSMutableData转换为NSString吗? - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response
我使用下面显示的代码下载文件.然后我试图将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 } 解决方法
你不能在你的应用程序包中写.您需要将其保存在其他位置,例如您的应用程序的Documents目录:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"file.txt"]; [data writeToFile:filePath atomically:YES]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |