ios - 无法在文件夹中写入 nsdata

标签 ios nsdata writetofile

代码如下:

NSData * imageData = [NSData dataWithContentsOfURL:imageURL];                

 [imageData writeToFile:savedImagePath options:NSDataWritingAtomic error:&error];
                            if(error != nil)
 NSLog(@"write error %@", error);   

错误:

 write error Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x8b7b850 {NSUnderlyingError=0x8b7d7c0 "The operation couldn’t be completed. No such file or directory", NSFilePath=/Users/alfa-1/Library/Application Support/iPhone Simulator/6.0/Applications/C24B228A-599E-4249-97A7-17775E8A546B/Library/Caches/ChannelListImages/http:/direct.domain.com/files/icons/1-all-cb.jpg, NSUserStringVariant=Folder}

最佳答案

在将数据写入文件之前。您需要创建文件夹。按照这些步骤

#define APPLICATION_DATA_DIRECTORY @"Application Data"
+ (NSString *)cachesDirectoryPath
// Returns the path to the caches directory.  This is a class method because it's
// used by +applicationStartup.
{
    NSString *      result;
    NSArray *       paths;

    result = nil;
    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    if ( (paths != nil) && ([paths count] != 0) ) {
        assert([[paths objectAtIndex:0] isKindOfClass:[NSString class]]);
        result = [paths objectAtIndex:0];
    }
    result = [result stringByAppendingPathComponent:APPLICATION_DATA_DIRECTORY];
    if (![[NSFileManager defaultManager] fileExistsAtPath:result]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:result withIntermediateDirectories:YES attributes:nil error:NULL];
    }

    return result;
}

在此之后:#define kPhotosDirectoryName @"ApplicationDocuments"

    NSMutableString *savePath = [NSMutableString string];
    [savePath appendFormat:@"%@/%@",[YOURClass cachesDirectoryPath],kPhotosDirectoryName];

    [savePath appendFormat:@"/%@",YOUR_FILE_NAME];

    if (![[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
        //write the data to file here
    }

关于ios - 无法在文件夹中写入 nsdata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15002520/

相关文章:

ios - 在 App 的整个生命周期中仅显示一次 View

ios - 从 NSData 加载 UIImage 导致不稳定的 UITableView 滚动

swift - ios9 缓存 NSData?

Ruby File.open 不创建文件

ios - 是否可以根据弹出窗口操作替换弹出窗口(或模态视图)后面的 UIView?

ios - @property from*.h 没有出现在 *.m 中

ios - 在 Objective C/ios 中本地保存文件

c++ - 如何让数组显示在文件中?

ios - Xcode 7/Swift : Save value of slider and send to child class when view changes

ios - 捕获 NSKeyedUnarchiver 异常