webview很容易造成內存泄漏, 所以非得用的話要盡可能進行優化, 不過話說回來, 要是webview很適合ios, 那還要ios開發干啥呢
@interface NARegisterServiceDelegateViewController ()<UIWebViewDelegate>
@property (nonatomic, retain) UIWebView *webView;
@property (nonatomic, assign) BOOL isSuccessfullyLoad;
@end
#pragma mark - 創建webview
- (void)createWebview{
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
[self.view addSubview:_webView];
_webView.delegate = self;
//適配屏幕
[_webView setScalesPageToFit:YES];
[self requestNetwork];
}
#pragma mark - 網絡請求
- (void)requestNetwork{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:SERVICE_DELEGATE_URL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:AF_REQUEST_TIMEOUT];
// NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:SERVICE_DELEGATE_URL]];
[_webView loadRequest:request];
}
#pragma mark - webview開始加載
- (void)webViewDidStartLoad:(UIWebView *)webView{
_isSuccessfullyLoad = NO;
}
#pragma mark - webview加載結束
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self memoryoptimalize];
[SVProgressHUD showSuccessWithStatus:@"加載成功"];
[SVProgressHUD dismissWithDelay:1.5];
_isSuccessfullyLoad = YES;
}
#pragma mark - webview加載失敗
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"服務條款加載失敗, 錯誤原因: %@", error);
if(error.code == -1009){
[self showLoadFailedAlertWithMessage:@"您似乎斷開了網絡連接"];
}
else if (error.code == -1001){
[self showLoadFailedAlertWithMessage:@"請求超時, 請重試"];
}
else{
[self showLoadFailedAlertWithMessage:@"抱歉, 加載失敗"];
}
_isSuccessfullyLoad = NO;
}
#pragma mark - 展示加載失敗的alert
- (void)showLoadFailedAlertWithMessage:(NSString *)message{
[SVProgressHUD showErrorWithStatus:message];
[SVProgressHUD dismissWithDelay:1.5];
}
#pragma mark - 內存優化
- (void)memoryoptimalize{
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的
[[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - 視圖將要出現
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if (!_isSuccessfullyLoad) {
[SVProgressHUD showWithStatus:@"正在拼命加載中, 請稍候..."];
}
}
#pragma mark - 視圖將要消失
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[SVProgressHUD dismiss];
// [_webView loadHTMLString:@"" baseURL:nil];
[_webView stopLoading];
}
#pragma mark - dealloc
- (void)dealloc{
_webView.delegate = nil;
}
感謝http://blog.csdn.net/primer_programer/article/details/24855329