-2

我有一个 iphone 应用程序,它使用 JSON 文件下载 pdf 文件 JSON 响应看起来像这样

{
    "resource_id":"1132",
    "name_en":"mpla mpla mpla",
    "name_cn":null,
    "product_id":"1064",
    "product":"mpla",
    "category":"mpla Literature",
    "fileURLString_en":"http://mpla.mpla.com/media/427/mpla.pdf",
    "fileURLString_en_date":"Mon, 03 Sep 2012 08:53:40 GMT",
    "fileURLString_cn":"http://mpla.mpla.com/media/427/mpla.pdf",
    "fileURLString_cn_date":"Mon, 03 Sep 2012 08:53:40 GMT",
    "thumbnailURLString_en":"http://mpla.mpla.com/media/1472/mpla.png",
    "emailURLString_en":null,
    "emailURLString_en_date":null,
    "descriptionString_en":null,
    "emailThumbnailURLString_en":null,
    "emailThumbnailURLString_en_date":null,
    "externalUrl":null
},

我想下载Library/Caches/en文件夹中的en文件和Library/Cashes/ch文件夹中的中文文件。

我正在使用 ASIHTTPRequest 作为通信部分!您对下载和保存文件到特定文件夹有什么建议(在代码中)?

到目前为止,这是我的代码:

        -(void)createDirectory:(NSString *)directoryName atFilePath:(NSString *)filePath
        {
    NSString *filePathAndDirectory = [filePath stringByAppendingPathComponent:directoryName];
    NSLog(@"%@",filePathAndDirectory);
    NSError *error;

    if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory withIntermediateDirectories:NO
                                                    attributes:nil
                                                         error:&error])
    {
        NSLog(@"Create directory error: %@", error);
    }
    }



NSString* filePath=[NSString stringWithFormat:@""];

        NSString *clanguage = [[NSLocale preferredLanguages] objectAtIndex:0];

        if([clanguage isEqualToString:@"en"])
        {
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            filePath = [NSString stringWithFormat:@"%@/en/%@",cachesPath,urlPath.lastObject];
        }
        else if([clanguage isEqualToString:@"zh-Hans"])
        {
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            filePath = [NSString stringWithFormat:@"%@/cn/%@",cachesPath,urlPath.lastObject];

        }

我尝试创建两个子文件夹,但无法根据链接将文件保存在其中。我还尝试将文件重命名为英文的名称和中文的ch_name,但这不方便!

4

1 回答 1

1

做这个:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
if(![fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:@"en/mpla.pdf"]]) {
    [downloadedPdfData writeToFile:cachePath options:NSDataWritingAtomic error:&error];

}
if(![fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:@"ch/mpla.pdf"]]) {
    [downloadedPdfData writeToFile:cachePath options:NSDataWritingAtomic error:&error];
}

从这里检查目录或文件是否存在

于 2012-09-25T10:53:47.353 回答