无法在Swift 2.0和Xcode 7中的WebView中加载本地HTML文件

时间:2015-10-08 13:42:38

标签: ios uiwebview swift2 xcode7 wkwebview

我有一个本地HTML(静态内容,里面没有链接)文件,需要在Web视图中加载。我已经使用UIWebView来加载它但是在升级到Swift 2.0和Xcode 7后,现有的实现在presentViewController行崩溃,我们尝试在其中呈现具有Web视图的View Controller,但之前它正在工作。由于WebKit引入似乎是问题,但它不应该影响现有的实施权利。那么任何人都可以帮助我或建议我最好的方式去? 该项目面向iOS 8及以上版本(仅限iPad)。 这是正在运行的代码

let path = NSBundle.mainBundle().URLForResource("index", withExtension: "html")   
let prepareRequest = NSURLRequest(URL: path!)  
self.webView.loadRequest(prepareRequest)

由于

Crash Report      
1   0x8707b09 StartWebThread()                                  
2   0x524d6b0 __pthread_once_handler     
3   0x523eebe _os_once     
4   0x524d65f pthread_once    
5   0x870789e WebThreadEnable     
6   0x75ce14a +[WebView(WebPrivate) enableWebThread]     
7   0x75cad90 WebKitInitialize        
8   0x2822a30 ___UIApplicationLoadWebKit_block_invoke      
9   0x4f0abef _dispatch_client_callout       
10  0x4ef4a92 dispatch_once_f       
11  0x4ef4922 dispatch_once       
12  0x2822940 _UIApplicationLoadWebKit        
13  0x4083461 _class_initialize          
14  0x408bfe5 lookUpImpOrForward           
15  0x408be8d _class_lookupMethodAndLoadCache3          
16  0x409612f objc_msgSend         
17  0x2cef77a UINibDecoderDecodeObjectForValue          
18  0x2cef9b0 UINibDecoderDecodeObjectForValue            
19  0x2cef4c3 -[UINibDecoder decodeObjectForKey:]        
20  0x289480c -[UIView initWithCoder:]        
21  0x28be337 -[UIScrollView initWithCoder:]         
22  0x2cef7ae UINibDecoderDecodeObjectForValue           
23  0x2cef4c3 -[UINibDecoder decodeObjectForKey:]         
24  0x2b6cbca -[UIRuntimeConnection initWithCoder:]       
25  0x2cef7ae UINibDecoderDecodeObjectForValue        
26  0x2cef9b0 UINibDecoderDecodeObjectForValue        
27  0x2cef4c3 -[UINibDecoder decodeObjectForKey:]
28  0x2b6be80 -[UINib instantiateWithOwner:options:]        
29  0x29860d4 -[UIViewController _loadViewFromNibNamed:bundle:]        
30  0x298686b -[UIViewController loadView]         
31  0x2986a9f -[UIViewController loadViewIfRequired] 

4 个答案:

答案 0 :(得分:0)

我在一个新项目上测试了你的代码,它并没有让我崩溃。升级到Xcode7时是否禁用了App Transport Security?

如果尚未将其禁用,请将其添加到plist中。

<key>NSAppTransportSecurity</key>
    <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

答案 1 :(得分:0)

来自文档:

  

使用loadHTMLString:baseURL:方法开始加载本地HTML文件或loadRequest:方法开始加载Web内容。

出于安全原因,他们可能已经改变了一些东西:

  

为了帮助您避免受到安全攻击,请务必使用此方法加载本地HTML文件;不要使用loadRequest:

我使用loadHTMLString:baseURL:并且像魅力一样工作。它需要一个字符串,因此您应该获取html文件的内容并将其存储在String中。

尝试这种方式让我知道

答案 2 :(得分:0)

您可以使用以下新的iOS9-only API:

  

func loadFileURL(_ URL: NSURL, allowingReadAccessToURL readAccessURL: NSURL) -> WKNavigation?

如果您的NSURL需要从捆绑包中加载资源,则第二个index.html应指向一个目录。

答案 3 :(得分:0)

我自己找到了答案。当我们使用dispatch_sync打开pop,我们可以避免崩溃,它对我有用。

dispatch_async(dispatch_get_main_queue()){() - &gt;无效    self.presentViewController(popoverViewController,animated:true,completion:nil)         }