如何在后台加载来自网址的许多照片(异步)

时间:2012-06-27 15:32:17

标签: objective-c asynchronous uiimageview nsurlconnection nsurl

我使用这种方法来加载许多图像以滚动视图,但是当从网址加载图像时我的滚动视图卡住了,我无法理解如何在后台加载它们以便用户不会感受它。

此方法会在"中呼叫几次(8);对于"周期。

- (void)loadPhotosToLeftscroll{

    //getting image information from JSON
    NSMutableDictionary *photoDict;
    photoDict = [leftPhotoArray lastObject];

    //getting the photo
    NSString *photoPath = [photoDict objectForKey:@"photos_path"];
    NSLog(@"photo Path:%@",photoPath);


    NSData * imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:photoPath]];    

            UIImage *image = [UIImage imageWithData:imageData];
            // use the image how you like, say, as your button background

            //calculating the hight of next photo
            UIImageView *leftImage = [leftBlockScroll.subviews lastObject];

            //allocating photoView
            UIImageView *photoView = [[UIImageView alloc]initWithFrame:CGRectMake(5 , leftImage.frame.origin.y + leftImage.frame.size.height+5, image.size.width/2, image.size.height/2 )];
            photoView.userInteractionEnabled=YES;
            [photoView.layer setMasksToBounds:YES];
            [photoView.layer setCornerRadius:3];


            //getting items list
            NSDictionary *sh_items = [photoDict objectForKey:@"items"];

            //adding image button
            UIButton *imageOverButton = [UIButton buttonWithType:UIButtonTypeCustom];
            imageOverButton.frame = CGRectMake(0, 0, photoView.frame.size.width, photoView.frame.size.height);
            [imageOverButton addTarget:self action:@selector(LeftimagePressed:) forControlEvents:UIControlEventTouchUpInside];
            [imageOverButton setTag:[leftPhotoArray count]-1];
            [photoView addSubview:imageOverButton];

            //adding sh button to imageView
            [self addThe_sh_signs:sh_items To_ImageView:photoView];

            //subViewing the image to the scrollView
            [self insert_Image:image toImageView:photoView in_Scroll:leftBlockScroll];

            //calclulating the position of next imageView in scroll.
            nextLeftPhotoHight = photoView.frame.size.height + photoView.frame.origin.y + 5;

            //calculating the hight of the highest scroll view in both.
            leftBlockScroll.contentSize = CGSizeMake(160, [self theSizeOfScrollViewHight]);
            rightBlocScroll.contentSize = CGSizeMake(160, [self theSizeOfScrollViewHight]);
            isLoadindContant = NO;
            [self.view reloadInputViews];
            [leftBlockScroll reloadInputViews];

}

请不要发送给我一些试图解释如何使用异步的链接。 尝试根据您在此处看到的方法进行解释。 我在这里提出任何问题,您需要请求帮助我。

1 个答案:

答案 0 :(得分:2)

您必须以适当的方式异步进行。我认为没有办法解决这个问题。我将一个UIImageView对象子类化,并将它的许多实例放在一个塔的单元格中(在你的情况下在滚动视图中)。使用url初始化子类对象并异步加载它们的图像(使用一些缓存,以便每次都不加载图像)。

本教程在一开始就帮助了我很多: http://www.markj.net/iphone-asynchronous-table-image/

您只需要将其用于滚动视图。背景原则保持不变。