在iOS中,加载app成功后bundle中的文件将被加载到.app包中,注意不要将该包中的文件移动到外部。
NSString *srcFilePath = [[NSBundle mainBundle] pathForResource:@"podFile" ofType:nil];
JCFilePersistence *fp = [JCFilePersistence sharedInstance];
NSString *desFilePath = [fp getDirectoryOfDocumentFileWithName:@"pdfFile"];
// [fp copyFileFromPath:srcFilePath toPath:desFilePath];
[fp moveFileFromPath:srcFilePath toPath:desFilePath];
#pragma mark - Move file
- (void)moveFileFromPath:(NSString *)srcFilePath toPath:(NSString *)desFilePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:srcFilePath]) {
if ([fileManager fileExistsAtPath:desFilePath]) { // 如果文件存在于目标路径中,先将其移除
NSError *removeError = nil;
[fileManager removeItemAtPath:desFilePath error:&removeError];
if (removeError) {
[JCAlert alertWithMessage:@"移除目标文件失败" Error:removeError];
return;
}
}
// 从源路径移动文件到目标路径
NSError *moveError = nil;
[fileManager moveItemAtPath:srcFilePath toPath:desFilePath error:&moveError];
if (moveError) {
[JCAlert alertWithMessage:@"移动文件出错" Error:moveError];
}
}
else {
#ifdef LOG_DEBUG
NSLog(@"移动文件失败,源文件不存在");
#endif
}
}
这个动作或许在模拟器中可以成功,但是来到真机设备上将会报错:“Cocoa error 513.”。
解决方法是不要move,而是copy:
- (void)copyFileFromPath:(NSString *)srcFilePath toPath:(NSString *)desFilePath {
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:srcFilePath]) {
if ([fileManager fileExistsAtPath:desFilePath]) { // 如果文件存在于目标路径中,先将其移除
NSError *removeError = nil;
[fileManager removeItemAtPath:desFilePath error:&removeError];
if (removeError) {
[JCAlert alertWithMessage:@"移除目标文件失败" Error:removeError];
return;
}
}
// 从源路径移动文件到目标路径
NSError *copyError = nil;
[fileManager copyItemAtPath:srcFilePath toPath:desFilePath error:©Error];
if (copyError) {
[JCAlert alertWithMessage:@"移动文件出错" Error:copyError];
}
}
else {
#ifdef LOG_DEBUG
NSLog(@"复制文件失败,源文件不存在");
#endif
}
}