+ 返回零

我使用这个代码从URL加载UIImage

  NSURL *imageURL = [NSURL URLWithString:@"http://testwebsite.com/image.png"]; NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageURL]; imageView.image = [UIImage imageWithData: imageData]; 

但我被卡在一个像这样的URL
http://www.testwebsite.com/getFile?userID=123
这在浏览器中正常工作,但在上面的imageDatavariables中返回nil。

我怎么能从这样一个模糊的URL加载图像(即从不显示文件名,而是redirect到图像文件的URL )?

先谢谢你。

因为一些奇怪的原因我必须使用:
[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

当我创build的URL ,这解决了这个问题。

NSData initWithContentsOfURL:如果数据无法加载(即,如果您收到HTTP错误代码),则返回nil

机会是你指向的URL有一些引用阻止程序或cookie的要求,防止它在你的应用程序内使用(只是一个问题的build议)。

我build议你看看使用下面的变种:

 - (id)initWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr 

如果返回值为零,请注意errorPtr的值。

例如:

 NSError *error; NSData* imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:@"http://example.com/notfound"] options:0 error:&error]; if(imageData == nil) { NSLog(@"Error: %@", error); } else { NSLog(@"Got %u bytes", imageData.length); } 

您可以看到以下错误:

 Error: Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn't be completed. (Cocoa error 256.)" UserInfo=0xa881c20 {NSURL=http://example.com/notfound} 

如果你像这样加载图像,它阻止了主线程,并且让你的应用程序没有响应,我不确定initWithContentsOfURL:方法是否处理redirect,如果这是问题…你可以创build另一个类(例如ImageFetcher )使用NSURLConnection并实现NSURLConnectionDataDelegate。 使用连接:willSendRequest:redirectResponse:方法从NSURLConnectionDataDelegate你可以处理redirect和在连接:didReceiveData:方法你可以追加接收到的数据到一个NSMutableData(并不保证你一次接收所有的数据)。 此外,如果您实现连接:didReceiveResponse:方法,则无需等待连接完成或下载任何数据,并检查响应是否显示错误,并在connectionDidFinishLoading:方法中调用另一种方法更新图像查看(或调用ImageFetcher类的委托与适当的数据更新图像视图)。

NSURL URLWithString:如果URL不符合RFC 2396,则返回nil,且必须转义

如果你通过链接阅读rfc2396 ,你会得到大量的细节

我发现一个很棒的网站,用来检查有问题的字符,selectURL的path选项

http://www.websitedev.de/temp/rfc2396-check.html.gz