現在在接觸iOS開發,今天在調試一個界面加載web頁面的問題,發現死活無法加載,瀏覽器里能正常打開,加上相應代碼之后得到了錯誤信息為:
2013-04-18 15:05:06.446 Client_DEMO[22889:1a303] webview didFailLoadWithError <UIWebView: 0x18ff2160; frame = (18 70; 315 408); autoresize = W+H; layer = <CALayer: 0xc1140a0>> , and err is Error Domain=WebKitErrorDomain Code=101 “The operation couldn’t be completed. (WebKitErrorDomain error 101.)”
加日志的辦法為:
WebviewDelegat.h 代碼如下:
#import <UIKit/UIKit.h>
@interface WebviewDelegate : NSObject <UIWebViewDelegate>
@end
WebviewDelegat.mm 代碼如下:
#import “WebviewDelegate.h”
@implementation WebviewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString * str = [[request URL] absoluteString];
NSString *urlStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray * strArray = [urlStr componentsSeparatedByString:@":"];
if([strArray count]>2)
{
NSLog(@”webview for %@”,urlStr);
if ([[strArray objectAtIndex:0] isEqualToString:@”jscall”] ) {
//這里攔截做些本地的事情
}
return NO;
}else{
return YES;
}
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@”webview webViewDidStartLoad %@”,webView.debugDescription);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@”webview webViewDidFinishLoad %@”,webView.debugDescription);
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
//把出錯信息打出來
NSLog(@”webview didFailLoadWithError %@ , and err is %@”,webView.debugDescription, error.debugDescription);
}
@end
通過UIWebView的setDelegate方法將其綁定。
網上搜索之后得知是urlencode有問題,仔細核實了一下url,發現url里有個參數值有豎線,於是知道了是豎線未轉義導致。
比如: http://lizongbo.com/?chid=0|0|618119, 應該為:http://lizongbo.com/?chid=0%7C0%7C618119
解決辦法很簡單,對url的字符串做了個替換:
sUrl=replaceStr(sUrl,”|”,”%7C”);//不轉義的話會報錯,nd err is Error Domain=WebKitErrorDomain Code=101 “The operation couldn’t be completed. (WebKitErrorDomain error 101.)”
參考:http://stackoverflow.com/questions/2028379/uiwebkit-error-101