Nee*_*raj 9 iphone nsurlconnection uiimage
我对iPhone开发很新,并尝试在我的应用程序中获取"来自服务器的图像".
我正在使用以下方法执行此操作:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
虽然我可以在调试器中看到Image对象的NSData有一些值(以字节为单位),但此函数不会返回预期的图像
虽然,从服务器获取文本的功能非常类似,但我获得了预期的值.
- (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];
}
Run Code Online (Sandbox Code Playgroud)
这种方法很好.
有人可以帮我理解为什么我没有从服务器获取图像?
谢谢
Gar*_*uma 29
如果您要做的只是通过URL从Web服务器获取图像,则有一种更简单的方法.
这是我使用的:
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString: @"http://example.com/image.jpg"]]];
Run Code Online (Sandbox Code Playgroud)
如果要在图像视图上使用它,请执行以下操作:
// Let's assume the picture is an instantiated UIImageView
[picture setImage: myImage];
[myImage release];
Run Code Online (Sandbox Code Playgroud)
我确信有一个人可能不想使用这种方法的原因,但我会从这开始,看看它是否能满足您的需求.