xcode 即使使用delegate = self,uiwebview也不会加载请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14613098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:40:29  来源:igfitidea点击:

uiwebview not loading request even with delegate = self

iosobjective-cxcodeuiwebviewuiwebviewdelegate

提问by rudirudi

I have created a NSObject class and included , in the init i create a uiwebview set the delegate to self and send the load request.

我创建了一个 NSObject 类并包含在初始化中我创建了一个 uiwebview 将委托设置为 self 并发送加载请求。

For some reason webViewDidFinishLoad or didFailLoadWithError never get fired. I can't figure why.

出于某种原因, webViewDidFinishLoad 或 didFailLoadWithError 永远不会被解雇。我想不通为什么。

//
//  RXBTest.h
#import <Foundation/Foundation.h>
@interface RXBTest : NSObject <UIWebViewDelegate>
@end


//  RXBTest.m
//  pageTest
#import "RXBTest.h"
@implementation RXBTest
- (id) init
{
     if((self=[super init])){
         UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
         [webView setDelegate:self];

         [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]];
     }
     return self;
}   
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
     NSLog(@"ERROR LOADING WEBPAGE: %@", error);
}
- (void) webViewDidFinishLoad:(UIWebView*)webView
{
     NSLog(@"finished");
}
@end

anybody has any ideas?

有人有任何想法吗?

thanks rudi

谢谢鲁迪

回答by Mathew

If you are using ARC, then the problem is that your webViewvariable is local to the initmethod and therefore is getting deallocated before the web view finishes loading. Try adding the web view as an instance variable:

如果您使用的是 ARC,那么问题在于您的webView变量是该init方法的本地变量,因此在 Web 视图完成加载之前被释放。尝试将 Web 视图添加为实例变量:

@interface RXBTest : NSObject <UIWebViewDelegate>
{
    UIWebView* webView;
}
@end

@implementation RXBTest
- (id) init
{
    if((self=[super init])){
        webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
        [webView setDelegate:self];

        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]]];
    }
    return self;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"ERROR LOADING WEBPAGE: %@", error);
}
- (void) webViewDidFinishLoad:(UIWebView*)webView
{
    NSLog(@"finished");
}
@end

If you are not using ARC, you will need to remember to release your webViewobject in the dealloc method as well.

如果您不使用 ARC,您还需要记住webView在 dealloc 方法中释放您的对象。

回答by rudirudi

you forgot to add this in your header file (.h):

您忘记在头文件 (.h) 中添加此内容:

#import <UIKit/UIWebView.h>