UIAlertView отчасти противоречит UIActivityIndicator - PullRequest
1 голос
/ 20 марта 2012

Я загружаю изображения из онлайн-изображения для кэша, когда в автономном режиме. Когда я открываю приложение, изображение полностью загружалось до появления UIAlertView. Это закончено неправильно. Я хочу сделать UIAlertView всплывающим перед загрузкой изображений. Здесь мой код ниже.

- (void) operatePopupUpdating {
    myAlert = [[UIAlertView alloc] initWithTitle:@"Updating database.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [myAlert show];

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    indicator.center = CGPointMake(myAlert.bounds.size.width / 2, myAlert.bounds.size.height - 50);
    [indicator startAnimating];
    [myAlert addSubview:indicator];

    [self operateUpdate];
    [self updateImage];

    [self operationCompleted];
}

В updateImage, operaUpdate и operationCompleted Method

- (void)updateImage {
NSString *snake_ico_file = @"snake_img_icn_";
NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:@"0.jpg"]];
int max_count = [[self readData] count];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    for (int i = 0; i < max_count; i++) {
        NSString *path = @"http://exitosus.no.de/drngoo/image/";
        path = [path stringByAppendingFormat:@"%d",i];
        NSString *ico_path = [path stringByAppendingFormat:@"/ico"];

        //icon            
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filename = [snake_ico_file stringByAppendingFormat:@"%d.jpg"];
        NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];
        NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:ico_path]];;
        [thedata writeToFile:localFilePath atomically:YES];
       }
}

-(void) operationCompleted
{
       [myAlert dismissWithClickedButtonIndex:0 animated:YES];

       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message form System" message:@"Database was updated successful" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

       [alert show];
}

- (void)operateUpdate {

     NSString *filePath = [self dataFileSettingPath];
     int updatedVer = 0;
     int version = [self checkDatabase];
     if (version == -1) {
         updatedVer = [self createDataBase:0];
     } else {
         updatedVer = [self updateDataBase:version];
     }

     [self.settingInfo setObject:[NSString stringWithFormat:@"%d",updatedVer] forKey:@"DBVersion"];
   [self.settingInfo writeToFile:filePath atomically:YES];
}

Как их исправить и правильно работать?

1 Ответ

1 голос
/ 20 марта 2012

alertView будет отображаться только после завершения загрузки изображения.Одним из решений этой проблемы является

Создание другого класса ImageDownLoad.h

в .h

@property(nonatomic,assign)id delegate;
@property(nonatomic,retain) NSString *path;

в .m

@synthesize delegate;
@synthesize path;

Создатьа именно метод,

-(void)startDownloadImageWithUrl:(NSURL*)imageUrl withLocalFilePath:(NSSTring*)filePath{
       path = filePath;
       receiveData = [NSMutableData data];
       NSURLRequest *request = [[NSURLRequest alloc]initWithURL:imageUrl];
       NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request];
 }

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
        [(id)delegate performSelector:@selector(SaveData:inFilePath:) withObject:receiveData withObject:path];
}

Это создаст соединение и начнет загружать ваше изображение в отдельный класс.Затем в своем ViewController добавьте немного кода, как показано ниже.

  - (void)updateImage {
          NSString *snake_ico_file = @"snake_img_icn_";
          NSString *filePath = [self dataFile:[snake_ico_file stringByAppendingString:@"0.jpg"]];
          int max_count = [[self readData] count];
          if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
                 for (int i = 0; i < max_count; i++) {
                 NSString *path = @"http://exitosus.no.de/drngoo/image/";
                 path = [path stringByAppendingFormat:@"%d",i];
                 NSString *ico_path = [path stringByAppendingFormat:@"/ico"];

                      //icon            
                 NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                 NSString *documentsDirectory = [paths objectAtIndex:0];
                 NSString *filename = [snake_ico_file stringByAppendingFormat:@"%d.jpg"];
                 NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:filename];

                 ImageDownLoad *imageDown = [[ImageDownLoad alloc]init];
                 imageDown.delegate = self;
                 [imageDown startDownloadImageWithUrl:[NSURL URLWithString:ico_path] withLocalFilePath:localFilePath];

            }
   }

Этот метод будет вызываться каждый раз, когда загрузка изображения завершается.

   -(void)SaveData:(NSData*)data inFilePath:(NSString*)filePath{

          [data writeToFile:filePath atomically:YES];

   }

Ваш пользовательский интерфейс не будет задерживаться, выполняя следующие действия:)

...