移动bundle中的文件时出现错误:Cocoa error 513

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值