Search code examples
cocoaswiftuiwebview

Why don't WebView previews show in Playgrounds?


In my Xcode playgrounds, I have been attempting to set up a WebView/UIWebView and have been unable to preview either the iOS or OS X version. When I try to run my code for iOS, I get this error in my console:

nwi_state: registration failed (1000000)

This error shows up as soon as I instantiate UIWebView. This is my code:

import UIKit

let wv = UIWebView(frame: CGRectMake(0, 0, 255, 255))
let url = NSURL(string: "http://www.google.com")
let req = NSURLRequest(URL: url!)
wv.loadRequest(req)
wv // This is for previewing in the Playground

When using Cocoa, I get no errors in my console but I am unable to preview the WebView by using the QuickLook icon or adding to my Timeline. My Cocoa code:

import Cocoa
import WebKit

let mainWeb = WebView(frame: NSRect(x: 0, y: 0, width: 255, height: 255))
let url = NSURL(string: "http://www.google.com")
let req = NSURLRequest(URL: url!)
mainWeb.mainFrame.loadRequest(req)
mainWeb // This is for previewing in the Playground

I'm running Xcode 6.1 on OS X Yosemite 10.10.1. My Internet connection is fine, and to the best of my knowledge I haven't modified any files that could potentially cause this kind of problem. What could potentially be the cause of this issue?


Solution

  • The function that is used for previewing views in playgrounds is XCPShowView(identifier: String,view: NSView/UIView). So this will work in an OS X playground:

    import Cocoa
    import WebKit
    import XCPlayground
    
    
    let mainWeb = WebView(frame: NSRect(x: 0, y: 0, width: 255, height: 255))
    let url = NSURL(string: "http://www.google.com")
    let req = NSURLRequest(URL: url!)
    mainWeb.mainFrame.loadRequest(req)
    XCPShowView("my web view", mainWeb)
    

    It seems that iOS playgrounds must be inside some Xcode project in order for the same thing to work. Additionally, 'Run in Full Simulator' option must be checked in the file inspector of that playground. After that the web view will appear with google page loaded, though accompanied by some nasty error message about failing to obtain sanbox extensions.