首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UIWebView loadRequest 崩潰:NSString 需轉 NSURL 參數類型錯誤

     編輯:程式設計綜合問答

錯誤代碼

[webView loadRequest:[NSURLRequest requestWithURL:[NSString stringWithFormat:@"https://site.com?status=%@", status]]];
// 崩潰:requestWithURL: 參數需 NSURL*,實際傳入 NSString*

修正代碼

NSString *urlString = [NSString stringWithFormat:@"https://site.com?status=%@", status];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

// 一行鏈式寫法
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://site.com?status=%@", status]]]];

關鍵點

  • NSURLRequest.requestWithURL: 參數類型為 NSURL *,非 NSString *。
  • NSURL.URLWithString: 將字符串轉為 URL 對象,會自動處理編碼(空格、中文等)。
  • 若 URL 包含中文/特殊字符,需 stringByAddingPercentEncodingWithAllowedCharacters::
NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encoded];

遷移建議:WKWebView

WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:[WKWebViewConfiguration new]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[wkWebView loadRequest:request];

避坑清單

  • 編譯器不會報錯(id 類型參數),運行時崩潰 unrecognized selector sent to instance。
  • NSURL 不支援 file:// 以外的本地路徑,本地 HTML 用 loadHTMLString:baseURL: 或 loadFileURL:allowingReadAccessToURL:。
  • iOS 9+ 默認阻止 HTTP 明文傳輸,需配置 NSAppTransportSecurity 或強制 HTTPS。

NSURLRequest 參數類型錯誤是新手高頻崩潰,牢記:字符串→NSURL→NSURLRequest→loadRequest,四步不亂序。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved