UIImageView занимает время для загрузки изображения

У меня возникла проблема, я хотел скачать изображение из Интернета по определенной ссылке. Загрузка этого изображения происходит в другом классе, который называется синглтон-класс moreAppInternet.m

Мой файл moreAppInterNet.m выглядит следующим образом

//finishImgDling is bool

// mutableData is NSMutableData

// urlConnection - это NSURLConnection

// appimage - это UIImage

// imageUrl - NSString, содержащий ссылку

+ (id) sharedManager {

static moreAppInterNet *sharedMyManager = nil;

@synchronized(self) {

    if (sharedMyManager == nil)

        sharedMyManager = [[self alloc] init];
}

return sharedMyManager;

}

- (void) downloadImageFromUrl {
FinishImDling = NO;

[self.mutableData setLength:0];

self.urlConnection = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.imageUrl]] delegate:self];


while(!finishedImgDling) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}   

}

- (недействительное) соединение:(NSURLConnection *) соединение didReceiveResponse: (NSURLResponse *) response {

if (connection == self.urlConnection)
{

    NSLog(@"imageDling");
}

}

- (недействительное) соединение:(NSURLConnection *) соединение didReceiveData: (NSData *) data {

if (connection == self.urlConnection)
{

    if (self.mutableData == nil)
    {
        self.mutableData = [NSMutableData data];
    }

    [self.mutableData appendData:data];
}

}

- (void) connectionDidFinishLoading:(NSURLConnection *) connection {

if (connection == self.urlConnection)
{
    NSLog(@"image Downloaded");

    finishedImgDling = YES;

    [self setUrlConnection:nil];

    [self storeImage];
}

}

- (void) storeImage {

[self setAppimage:nil];

self.appimage = [UIImage imageWithData:self.mutableData];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];     
NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *path =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"appImage.png"]];

[fileManager createFileAtPath:path contents:UIImagePNGRepresentation(self.appimage) attributes:nil];

 NSLog(@"downloading and storing complete");

}

и мой другой ViewController является следующим, откуда я вызываю эту функцию

- (void) viewDidLoad {

[moreAppInterNet sharedManager];

[self downloadImage];

}

- (void) downloadImage {

 NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download_Image_from_other_class) object:nil];

NSOperationQueue *que = [[NSOperationQueue alloc] init];

[que addObserver:self forKeyPath:@"operations" options:0 context:NULL];

[que addOperation:operation];

[operation release];

self.dlingQue = que;

[que release];

}

- (void) download_Image_from_other_class {

[[moreAppInterNet sharedManager] downloadImageFromUrl];

}

- (void) Наблюдать за ValueForKeyPath:(NSString *)keyPath ofObject:(id) изменение объекта:(NSDictionary *) изменить контекст: (void *) context {

if ([keyPath isEqualToString:@"operations"] && object == self.dlingQue)
{

    if ([self.dlingQue operationCount] == 0)
    {

        self.imgView = [[moreAppInterNet sharedManager] appimage];

        //it takes lots of time to display image in UIImageView
        //Even though Above line get executed
    }
}
else {

    [super observeValueForKeyPath:keyPath ofObject:object
                           change:change context:context];
}

}

Проблема в том, что self.imgView занимает много времени, чтобы загрузить изображение приблизительно за 5 секунд, даже если оно полностью загружено

Может кто-нибудь помочь мне или сказать мне, что я делаю не так

2 ответа

Библиотека, которую я использую для работы в сети - AFNetworking

Я думаю, ваш код загружает изображение снова, когда вы запрашиваете его.

Вам нужно проверить, есть ли у вас файл в downloadImageFromUrl,

Возможно, вам нужна более надежная библиотека для загрузки файлов.

Другие вопросы по тегам