Télécharger des fichiers image ou mp3 à partir du Web vers le répertoire iPhone de documentsTélécharger des fichiers image ou mp3 à partir du Web vers le répertoire iPhone de documents
Salut tout le monde
J'utilise ce code pour télécharger des fichiers de mon Web Site
Tout d'abord, je vérifie si le fichier existe
- (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];
}
Ce code pour le téléchargement:
- (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");
}
}
L'impression du journal « succès » mais pas copier le fichier dans le document Directory !!
façon simple et facile à cette utilisation AFNetworking https : //github.com/AFNetworking/AFNetworking –