UIWebView不显示我的网页 [英] UIWebView not displaying my webpage

查看:51
本文介绍了UIWebView不显示我的网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于某些背景信息,我要显示的网页是当前托管在AWS EC2上的Web应用程序.后端是带有Flask的Python,前端是简单的HTML/CSS.该URL具有HTTP,因为它尚未通过HTTPS进行保护.打开此网页的URL时,浏览器首先询问的是登录凭据(浏览器询问的不是网站).此页面 确实在我的iPhone上的移动Safari中加载,并且Safari确实成功要求提供凭据.如果我输入正确,它将正确加载页面.

For some background info, the webpage I'm trying to display is a web app currently being hosted on AWS's EC2. The backend is Python w/ Flask and the frontend is just simple HTML/CSS. The URL has HTTP, as it isn't secured with HTTPS yet. When the url for this webpage is opened, the first thing the browser asks is for login credentials (the browser asks, not the website). This page does load in mobile Safari on my iPhone, and Safari does successfully ask for the credentials. If I enter them in correctly, it will correctly load the page.

因此,我尝试使用应用程序传输安全性设置"下的允许任意加载"以及使用以下键的自定义例外域:

So I've tried both Allow Arbitrary Loads under App Transport Security Settings as well as a customized Exception Domain with the following keys:

App Transport Security Settings                         Dictionary
Exception Domains                                       Dictionary
    my website URL                                      Dictionary
        NSIncludesSubdomains                            Boolean (YES)
        NSExceptionAllowsInsecureHTTPLoads              Boolean (YES)
        NSThirdPartyExceptionAllowsInsecureHTTPLoads    Boolean (YES)
        NSExceptionMinimumTLSVersion                    String (TLSv1.0)
        NSExceptionRequiresForwardSecrecy               Boolean (YES)

但是,每当我在模拟器上启动该应用程序时,我得到的只是一个白屏(如果需要,可以发布屏幕截图).

However, whenever I launch the app on the simulator all I'm getting back is a white screen (can post screenshot if needed).

这是我在ViewController.swift中的代码:

Here's my code in ViewController.swift:

import UIKit

class ViewController: UIViewController {

     @IBOutlet var WebView: UIWebView!

     override func viewDidLoad() {
         super.viewDidLoad()
         let url = NSURL(string: "My URL inserted here")
         let request = NSURLRequest(URL: url!)
         WebView.loadRequest(request)
     }
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
     }
 }

如果我使用允许任意加载,当我在输出框中查看时,它会 说"应用传输安全性已阻止明文HTTP(http://)资源加载,因为它是不安全的.可以通过应用的Info.plist文件配置临时异常.当我正确配置Exception Domain(删除了允许任意加载")后,它不会给我消息之一.仅在某些情况下,当我使用例外域"更改设置时(同样,删除了允许任意加载"),我才会获得此输出.

If I use Allow Arbitrary Loads, when I look in the output box, it does not say "App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file." When I configure the Exception Domain correctly (with Allow Arbitrary Loads removed) it won't give me the message either. Only sometimes when I change around the settings using Exception Domain (again, with Allow Arbitrary Loads removed) do I get this output.

我开始认为该问题已超出安全性,非常感谢我可以采取任何尝试或解决此问题的建议或步骤!

I'm starting to think the issue goes beyond security, and any advice or steps I could take to try and fix this issue would be much appreciated, thanks!

推荐答案

白屏有点奇怪,假设401会导致出现标准错误页面,但是服务器可能为此设置了白页面.我的猜测是直接在URL中设置用户名和密码是行不通的,您无论如何都不应该这样做,而要依靠 WKWebView webView:didReceiveAuthenticationChallenge:委托方法.

The white screen is a bit odd, assuming that a 401 would result in a standard error page, but maybe the server set up a white page for this. My guess is that setting username and password directly in the URL doesn't work, you shouldn't do that anyways, but instead rely on WKWebView's webView:didReceiveAuthenticationChallenge: delegate method.

以下示例代码有望正常工作/提供帮助:

Here's some sample code hopefully working/helping:

#import "ViewController.h"
@import WebKit;

@interface ViewController () <WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:[WKWebViewConfiguration new]];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView setTranslatesAutoresizingMaskIntoConstraints:NO];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_webView]-0-|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_webView)]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_webView]-0-|"
                                                                      options:NSLayoutFormatDirectionLeadingToTrailing
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(_webView)]];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSURL *target = [NSURL URLWithString:@"http://yourhost.com/possiblePage.html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:target];
    [self.webView loadRequest:request];
}

- (void)webView:(WKWebView *)webView 
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
                completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {

    NSURLCredential *creds = [[NSURLCredential alloc] initWithUser:@"username" 
                                                          password:@"password" 
                                                       persistence:NSURLCredentialPersistenceForSession];
    completionHandler(NSURLSessionAuthChallengeUseCredential, creds);
}

@end

这基本上是一个简单的 ViewController 的实现文件(例如来自XCode的单个视图模板).它还显示了如何添加 WKWebView .一定要确保检查出所有委托方法,这样您就知道事情可以为您做些什么.

This is basically the implementation file of a simple ViewController (like from the single view template of XCode). It also shows you how you can add a WKWebView. Definitely make sure to check out all the delegate methods and such so you know what the thing can do for you.

很明显,必须以某种方式设置密码和用户名,我想您可以使用一个简单的警报弹出窗口让用户输入此信息(原则上类似于Safari).对于第一个测试,您可以对其进行硬编码.另请注意,我在此处设置了一个示例子页面,只使用与台式机浏览器通常使用的完全相同的URL.哦,而且由于服务器没有SSL,因此您需要允许任意加载.

Obviously, password and username have to be set somehow, I guess you can use a simple alert popup to have the user enter this info (this would be similar to Safari in principle). For the first test you can just hardcode it. Also note I set a sample subpage there, just use the exact same URL you would usually use on a desktop browser. Oh, and since the server doesn't have SSL, you need to allow arbitrary loads.

RPM在下面给出了一个很好的相关评论(谢谢),这是我最初没有想到的.该方法可能(实际上很有可能)会被多次调用.这最终还取决于您加载的网站.RPM解释了为什么网站可能会显示为纯白色.

RPM gave a good related comment below (thanks) that I had not originally thought about. The method may (actually will very likely) be called multiple times. This ultimately also depends on the website you load. RPM's explanation for why a site may appear plain white is spot on.

无论如何,上面的 webView:didReceiveAuthenticationChallenge:completionHandler:方法仅是一个简单的示例,假设您知道PW和用户名.通常,它会更复杂,您不应在每次要求用户输入凭据时都打开输入对话框.实际上,提供的 challenge 提供了一些方法,可以将对此委托方法的特定调用设置为与先前的调用相关.例如,它具有可能已经设置的 proposedCredential 属性.(如果是加载多个我不知道的资源的情况,请尝试一下.)此外,请检查其 previousFailureCount 等.很多情况可能取决于您加载的网站及其所需的内容.

In any way, the webView:didReceiveAuthenticationChallenge:completionHandler: method above is just a simple example assuming you know the PW and username. Generally it will be more complex and you shouldn't just open an input dialog every time it is called for the user to enter credentials. As a matter of fact, the provided challenge offers ways to set a specific call to this delegate method into relation to previous calls. For example, it has a proposedCredential property that may already have been set. (Whether that's the case for loading multiple resources I don't know on the top of my head, just try that out.) Also, check its previousFailureCount, etc. A lot of this may depend on the site you load and what it needs to get.

这篇关于UIWebView不显示我的网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆