簡體   English   中英

+ [NSURL URLWithString:]返回nil

[英]+[NSURL URLWithString:] returning nil

我使用此代碼從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
這在瀏覽器中工作正常,但在上面的imageData變量中返回nil。

如何從這樣一個模糊的URL加載圖像(即從一個不顯示文件名但重定向到圖像文件的URL )?

先感謝您。

由於一些奇怪的原因,我必須使用:
[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

當我創建URL並解決了這個問題。

NSData initWithContentsOfURL:如果無法加載數據,則返回nil (即,如果您收到HTTP錯誤代碼)。

有可能是您指向的URL有一些引用阻止程序或cookie要求阻止在您的應用程序中使用它(只是問題的一個建議)。

我建議您使用以下變體來代替:

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

如果返回值為nil,請注意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:方法是否正在處理重定向(如果這是問題)...您可以創建另一個類(例如ImageFetcher) )使用NSURLConnection並實現NSURLConnectionDataDelegate。 使用連接:來自NSURLConnectionDataDelegate的willSendRequest:redirectResponse:方法可以處理重定向,在連接中:didReceiveData:方法可以將接收到的數據附加到NSMutableData(不能保證一次接收所有數據)。 此外,如果實現連接,則不必等待連接完成或下載任何數據:didReceiveResponse:方法並檢查響應是否指示錯誤,並且在connectionDidFinishLoading:方法中,您可以調用另一種方法來更新圖像view(或使用適當的數據調用ImageFetcher類的委托來更新圖像視圖)。

NSURL URLWithString:如果URL不符合RFC 2396,@“”將返回nil並且必須轉義它們

如果您通過鏈接閱讀rfc2396 ,您將獲得大量詳細信息

我發現一個很棒的網站,用於檢查違規字符的位置,選擇URL的路徑選項

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM