使用NSURLConnection将图像加载到UIImageView中

时间:2011-02-22 03:52:20

标签: iphone iphone-sdk-3.0 ios4 uiimage

嘿所有人。我真的很擅长这个obj-c / xcode的东西。我正在尝试加载我的xib文件的背景。要做到这一点,我正在使用UIImageView并使用我从网上找到的图像填充它。问题在于它真的很慢。感觉像是在崩溃,但事实并非如此。我被告知使用NSURLConnection来解决问题,但不知道如何。这是我以前使用的代码。

wallpaper.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://mysite.com/mobile/wallpaperR.asp?id=%i",customerID]]]];

如何将上述代码翻译成NSURLConnection等效代码?

3 个答案:

答案 0 :(得分:6)

NSURLConnection将在新线程中下载数据,因此您的应用程序会感觉更快。

这很容易实现,但它确实需要您理解委派的概念。

我创建了一个有用的类来处理不同线程上的图像下载,我将与您共享代码,并提供注释以告知您发生了什么:

AsyncImage.h

AsyncImage.m

如果你需要帮助实现它,只需发表评论,我可以帮助你让它工作,我记得当我开始开发时,这对我来说也是痛苦的。

答案 1 :(得分:1)

你需要在使用webservice时对此进行解析。就像这个

-(void)startParsingForPhotoAlbumList:(NSString*)providerIdString
{
    NSString *urlString = [NSString stringWithFormat:@"http://YourUrl/showalbumxml.php?id=%@&show=show",providerIdString];
    NSURL *xmlURL = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL:xmlURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]autorelease];
    NSURLResponse *returnedResponse = nil;
    NSError *returnedError = nil;
    NSData *itemData  = [NSURLConnection sendSynchronousRequest:request returningResponse:&returnedResponse error:&returnedError];
    self.xmlParser = [[NSXMLParser alloc] initWithData:itemData];       
    [xmlParser setDelegate:self];
    [xmlParser parse];
}

并且需要实现解析器的委托方法作为示例。

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    if ([[[resultArray objectAtIndex:1]objectForKey:@"Transaction"]isEqualToString:@"Myapp/snaps"]) 
    {
        [(LoginViewController *)obj getRegisterResult:resultArray];
    }
}

然后在你的Viewcontroller中访问数据,从解析中你需要使用数组或字典传递对象。

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:itemImagePath]];
UIImage *image = [[UIImage alloc] initWithData:imageData];

答案 2 :(得分:0)

有一个例子可能有所帮助:

NSURLConnection loading image example