从URL /服务器获取图像 [英] Getting Image from URL/server

查看:107
本文介绍了从URL /服务器获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对iPhone开发很新,并尝试在我的应用程序中获取来自服务器的图像。

I'm fairly new to iPhone development and trying to fetch 'Images from Server' in my application.

我正在使用以下方法执行此操作:

I'm using the following method to do this:

- (UIImage *)imageFromURLString:(NSString *)urlString 
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];

    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request          
    returningResponse:&response error:&error];
    [request release];
    [self handleError:error];
    UIImage *resultImage = [UIImage imageWithData:(NSData *)result];

    NSLog(@"urlString: %@",urlString);
    return resultImage;
}

虽然我可以在调试器中看到NSData,但此函数不会返回预期的图像对于Image对象有一些值(以字节为单位)

This function does not return the expected image although I can see in debugger that NSData for the Image object has some value (in bytes)

虽然,一个非常类似的函数从服务器获取文本工作,我得到预期的值。

Although, a very similar function for getting text from server works and I get expected values.

- (NSString *)jsonFromURLString:(NSString *)urlString
{

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"GET"];

    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request
    returningResponse:&response error:&error];
    [request release];
    [self handleError:error];
    NSString *resultString = [[NSString alloc] initWithData:result
    encoding:NSUTF8StringEncoding];

    return [resultString autorelease];
}

此方法正常。

有人可以帮我理解为什么我没有从服务器上获取图像吗?

Could someone please help me in understanding why I'm not getting the Image from server?

谢谢

推荐答案

如果您要做的只是通过URL从Web服务器获取图像,则有一种更简单的方法。

If all you are trying to do is grab an image from a web server via a URL there is an easier way.

这就是我使用的:

UIImage* myImage = [UIImage imageWithData: 
    [NSData dataWithContentsOfURL: 
    [NSURL URLWithString: @"http://example.com/image.jpg"]]];

如果您想在图像视图中使用它,请执行以下操作:

And if you want to use it on an image view just do the following:

// Let's assume the picture is an instantiated UIImageView
[picture setImage: myImage];
[myImage release];

我确信有人可能不想使用这种方法,但我会从这开始,看看它是否能满足您的需求。

I'm sure there are reasons why a person might not want to use this approach, but I would start with this and see if it will do what you need it to.

这篇关于从URL /服务器获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆