【问题标题】:UIWebView Launch in SafariUIWebView 在 Safari 中启动
【发布时间】:2013-09-18 19:24:34
【问题描述】:

我知道这个问题已经被多次提及,并且在这个网站上的回答是两倍,但是我想我可能有一些不同的地方,需要知道是否可行。

我正在尝试将网站上的横幅广告加载到应用程序的 UIWebView 中。所有这些都完美无缺。但是,无论我尝试实现什么代码,我都无法获得它,因此当在应用程序中点击广告时,它将在 safari 中启动。

基本上我想拥有自己的广告服务器。该广告是托管在我们网站上的托管广告。横幅有服务器嵌入其中的链接。

这是我正在使用的代码。

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    NSString *string;
    string = @"http://www.samplesite.com/mobile_ads";
    NSURL *url = [NSURL URLWithString: string];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [self.adBox loadRequest:requestObj];
}

-(BOOL) adBox:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest    navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
    [[UIApplication sharedApplication] openURL:[inRequest URL]];
    return NO;
}

return YES;
}

关于我应该去哪里的任何想法?

【问题讨论】:

    标签: ios uiwebview safari


    【解决方案1】:

    在您的UIWebViewDelegatewebView:shouldStartLoadWithRequest:navigationType: 方法中,执行以下操作(假设您的广告的部分网址可识别):

    - (void)methodThatCreatesTheWebview {
      UIWebView *webview = [[UIWebView alloc] init];
      webview.delegate = self;
    }
    
    
    // Portion of the URL that is only present on ads and not other URLs.
    static NSString * const kAd = @"adSubdominOrSubDirectory";
    
    // pragma mark - UIWebViewDelegate Methods
    
    - (BOOL)webView:(UIWebView *)webView
        shouldStartLoadWithRequest:(NSURLRequest *)request
                    navigationType:(UIWebViewNavigationType)navigationType
    {
      if ([request.URL.absoluteString rangeOfString:kAd] !=  NSNotFound) {
        // Launch Safari to open ads
        return [[UIApplication sharedApplication] openURL:request.URL];
      } else {
        // URL isn't an ad, so just load it in the webview.
        return YES;
      }
    }
    

    【讨论】:

    • 创建 webview 时,将管理它的视图控制器添加为其委托。这将导致它在某些事件发生时(例如,当 URL 即将更改时)接收回调。有关委托模式的更多信息,请参阅 Objective-C 编程中的概念:developer.apple.com/library/ios/documentation/general/…
    • 我一直发现苹果文档比有用更令人困惑。我明白你在说什么,但我仍然不知道它属于哪里。
    • 即使在完成了大部分代码和展示位置之后,它也不起作用。
    • openURL: 将在成功时返回 YES。如果你从 webView:shouldStartLoadWithRequest:navigationType: 返回 YES,它也会在你的 webview 中加载那个 URL;可能不是你想要的。我认为那行代码应该是return ![[UIApplication sharedApplication] openURL:request.URL];
    猜你喜欢
    • 1970-01-01
    • 2012-10-06
    • 2023-03-22
    • 2015-09-29
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2015-03-07
    相关资源
    最近更新 更多