2013-04-09 4 views
0

У меня проблема с моими загруженными изображениями с моего сайта.IOS, чтобы показать загруженное изображение в окне коллекции

My CollectionView показывает изображение, когда оно уже добавлено в мой проект, но когда я загрузил новые изображения из файла Pictures.plist. У меня ничего нет.

Я проверяю перед загрузкой, если изображение уже загружено или нет. Но ... я не знаю.

Вот мой код:

#pragma mark - Téléchargement d'un fichier image mis à jour 
- (void)downloadImageFileIfUpdated:(NSString *)file withPath:(NSString *)urlPath { 

    //NSLog(@"[downloadImageFileIfUpdated withPath]"); 
    BOOL downloadFromServer = NO; 

    /// Définition de l'adresse du fichier serveur 
    NSURL *url = [NSURL URLWithString:[urlPath stringByAppendingString:file]]; 
    //NSLog(@"Téléchargement de l'entête HTTP depuis : %@", url); 

    /// Récupération du fichier local 
    NSArray *picturesInfosPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *picturesInfosDirectoryPath = [picturesInfosPath objectAtIndex:0]; 
    NSString *cachedPath = [picturesInfosDirectoryPath stringByAppendingPathComponent:file]; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 

    NSString *lastModifiedString = nil; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    [request setHTTPMethod:@"HEAD"]; 
    NSHTTPURLResponse *response; 
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL]; 
    if([response respondsToSelector:@selector(allHeaderFields)]) { 
     lastModifiedString = [[response allHeaderFields] objectForKey:@"Last-Modified"]; 
    } 

    NSDate *lastModifiedServer = nil; 
    @try { 
     NSDateFormatter *df = [[NSDateFormatter alloc] init]; 
     df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'"; 
     df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
     df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
     lastModifiedServer = [df dateFromString:lastModifiedString]; 
    } 
    @catch(NSException * e) { 
     NSLog(@"Error parsing last modified date : %@ - %@", lastModifiedString, [e description]); 
    } 
    //NSLog(@"Dernière modification du fichier serveur : %@", lastModifiedServer); 

    NSDate *lastModifiedLocal = nil; 
    if([fileManager fileExistsAtPath:cachedPath]) { 
     NSError *error = nil; 
     NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:cachedPath error:&error]; 
     if (error) { 
      NSLog(@"Error reading file attributes for : %@ - %@", cachedPath, [error localizedDescription]); 
     } 
     lastModifiedLocal = [fileAttributes fileModificationDate]; 
     //NSLog(@"Dernière modification du fichier local : %@", lastModifiedLocal); 
    } 

    /// Activation du téléchargement si on a pas de fichier local 
    if(!lastModifiedLocal) { 
     downloadFromServer = YES; 
    } 

    /// Activation du téléchargment si le fichier serveur Pictures.plist possède une mise à jour 
    if([lastModifiedLocal laterDate:lastModifiedServer] == lastModifiedServer) { 
     downloadFromServer = YES; 
    } 

    /// Téléchargement du fichier serveur 
    if(downloadFromServer) { 
     //NSLog(@"Télécharment du nouveau fichier serveur"); 
     NSData *data = [NSData dataWithContentsOfURL:url]; 
     if(data) { 
      /// Enregistrement du fichier 
      if([data writeToFile:cachedPath atomically:YES]) { 
       //NSLog(@"Téléchargement du fichier sauvé à : %@.", cachedPath); 
      } 
      /// Déclaration de la date de modification du fichier local en accord avec celle du fichier du serveur 
      if(lastModifiedServer) { 
       NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:lastModifiedServer forKey:NSFileModificationDate]; 
       NSError *error = nil; 
       if([fileManager setAttributes:fileAttributes ofItemAtPath:cachedPath error:&error]) { 
        //NSLog(@"File modification date updated."); 
       } 
       if(error) { 
        // NSLog(@"Error setting file attributes for: %@ - %@.", cachedPath, [error localizedDescription]); 
       } 
      } 
     } 
    } 
} 


#pragma mark - Initialisation des informations 
-(void) initializeViewWithFile:(NSString *)file { 

    NSLog(@"[initializeViewWithFile]"); 
    /// Arrêt de l'indication de chargement de la vue 
    [loadingView stopAnimating]; 

    NSString *fileName = [file stringByDeletingPathExtension]; 
    NSString *fileExtension = [file pathExtension]; 
    NSString *fileLocalPath; 
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    fileLocalPath = [rootPath stringByAppendingPathComponent:file]; 
    if(![[NSFileManager defaultManager] fileExistsAtPath:fileLocalPath]) { 
     fileLocalPath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension]; 
    } 
    NSDictionary* dictFromFile = [[NSDictionary alloc] initWithContentsOfFile:fileLocalPath]; 
    NSMutableArray* arrayFromFile = [dictFromFile objectForKey:@"Root"]; 

    /// Création d'un tableau qui contient les objets images 
    gallery = [[NSMutableArray alloc] init]; 
    NSEnumerator *enumerator = [arrayFromFile objectEnumerator]; 
    NSDictionary *obj; 
    while((obj = [enumerator nextObject])) { 
     PMPicture *picture = [[PMPicture alloc] initWithDictionaryFromPlist: obj]; 
     [gallery addObject: picture]; 
     [self downloadImageFileIfUpdated:picture.file withPath:picture.url]; 
    } 

    /// Initialisation 
    [galleryCollectionView setDataSource:self]; 
    [galleryCollectionView setDelegate:self]; 
    [galleryCollectionView reloadData]; 
} 

Коллекция Просмотр Методы:

#pragma mark - UICollectionViewDataSource 

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { 

return 1; 
} 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection: (NSInteger)section { 

return gallery.count; 
} 

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"GalleryCell"; 
PMPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; 
PMPicture *picture = [gallery objectAtIndex:indexPath.item]; 

// UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100]; 
// cellImageView.image = [UIImage imageNamed:[picture file]]; 

NSString *image = [picture file]; // NOT WORKING, BUT IS LIKE @"img23.png" 
//NSString *image = @"radios.png"; // WORK, I THINK BECAUSE IS ADDED IN PROJECT 
//NSLog(@"Image affichée : %@", image); 
[[cell cellImage] setImage:[UIImage imageNamed:image]]; 
return cell; 
} 

Вот это, если вы можете помочь мне, я ценю много!

мой взгляд начинается с initializeViewWithFile:file, где файл находится myPictures.plist

Благодаря

ответ

0
NSString *ImagePath = @"Full Path of Image"; 
[img setImage:[UIImage imageWithContentsOfFile:ImagePath] forState:UIControlStateNormal]; 
  1. Здесь я дал пример, который разработан для me..in ImageView. Спасибо.
Смежные вопросы