繁体   English   中英

从Web将图像或mp3文件下载到iPhone文档目录

[英]Download image or mp3 files from Web to iPhone document directory

从Web将图像或mp3文件下载到iPhone文档目录

嗨,大家好

我正在使用此代码从我的网站下载文件

首先,我检查文件是否存在

- (void)checkFile
{

    image_path = @"background2.jpg";

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryDirectory = [paths objectAtIndex:0];

    NSString *myFilePath = [libraryDirectory stringByAppendingPathComponent:image_path];

    BOOL fileExists = [fileManager fileExistsAtPath:myFilePath];

    if (fileExists) {
        NSLog(@"file exist");
        self.myImage.image = [UIImage imageWithContentsOfFile:myFilePath];

    } else {
        NSLog(@"file not exist");

        [self downloadImageFile:@"http://www.alhikmeh.org/images/background2.jpg" newFileName:image_path];



}

此代码下载:

- (void)downloadImageFile:(NSString *)path newFileName:(NSString *)newFileName
{
    NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    NSData *data = [NSData dataWithContentsOfURL:URL];

    if (data == nil) {
        NSLog(@"error");

    }
    NSString *appDocDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *storePath = [appDocDir stringByAppendingPathComponent:newFileName];
    BOOL success = [data writeToFile:storePath atomically:YES];

    if (success) {
        NSLog(@"success");
    } else {
        NSLog(@"not copied");
    }


}

日志打印“成功”,但未将文件复制到文档目录中!!

让我们尝试:(请参阅我的评论)

- (void)downloadImageFile:(NSString *)path newFileName:(NSString *)newFileName
{
NSURL *URL = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSData *data = [NSData dataWithContentsOfURL:URL];

if (data == nil) {
    NSLog(@"error");

}
NSString *appDocDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [appDocDir stringByAppendingPathComponent:newFileName];
// My comment : make sure that you check whether this file exists at above path???
// I run this code, and it can save data.
NSlog(@"%@",storePath);
BOOL success = [data writeToFile:storePath atomically:YES];

if (success) {
    NSLog(@"success");
} else {
    NSLog(@"not copied");
}
}

我使用您的代码成功,请检查您的文档目录。路径为

/Users/userName/Library/Application Support/iPhone Simulator/7.1/Applications/your project/Documents/background2.jpg

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM