我正在用ios8实现扩展。在这个import函数中,返回一个url。我需要从其中读取数据并保存到我的应用程序中。
下面是代码。
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *data;
[fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
data = [NSData dataWithContentsOfURL:newURL];
//saving in document directory
}];我的问题是,如果文件太大,dataWithContentsOfURL会因为内存不足而导致崩溃。
我想要一种方法,可以从url中读取数据,保存在我的文档中,然后读取下一部分并继续追加。因此,它不会有内存问题。
有人能帮帮忙吗。
发布于 2015-07-03 13:54:19
找到了两个解决方案。1-使用的NSURLConnection。使用NSFileHandle在文件中写入数据。
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1{
// [data appendData:data1];
[self.currentFileHandle seekToEndOfFile];
[self.currentFileHandle writeData:data1];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.currentFileHandle closeFile];
self.currentFileHandle = nil;
}nil协调器* fileCoordinator = [NSFileCoordinator alloc :nil];
[newURL协调读取项目属性:url options:NSFileCoordinatorReadingWithoutChanges错误:nil byAccessor:^(NSURL *fileCoordinator) {
NSFileManager * fileManager = [NSFileManager分配初始化];
NSError * error;
NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *urlDestination = [paths lastObject];
urlDestination = [urlDestination URLByAppendingPathComponent:[url lastPathComponent]];
if([[NSFileManager defaultManager] fileExistsAtPath:[urlDestination relativePath]]){
[[NSFileManager defaultManager] removeItemAtPath:[urlDestination relativePath] error:nil];
}BOOL success = fileManager copyItemAtURL:url浏览:url目标错误:&error;if (成功){} }];
我使用了第二个解决方案。抱歉,对齐错误。我试了很多,但还是不能很好地来。
https://stackoverflow.com/questions/31161185
复制相似问题