Search code examples
xcodeswifthttpsnsurlsessionswift-playground

NSURLErrorFailingURLPeerTrustErrorKey in Swift playground


The playground code at the bottom works as expected when the URL is

http://www.apple.com

and fails when the URL is

https://www.apple.com

NSURLErrorFailingURLPeerTrustErrorKey

I'm guessing that there is something wrong with sharedSession and https? Any suggestions?

// Playground - noun: a place where people can play

import Foundation
import XCPlayground

//  allow the asynchronous task to continue, set timeout in console

XCPSetExecutionShouldContinueIndefinitely()

let plainURL = NSURL(string: "https://www.apple.com/")

var session = NSURLSession.sharedSession()

func firstHandler(data:NSData!, response:NSURLResponse!, error: NSError!) {
    if let err = error {
        println("WTF error: \(error), \(error.userInfo)")
    }
    else {
        println("No error!")
        print(NSString(data: data, encoding: NSUTF8StringEncoding)!)
    }
}

var plainTask:NSURLSessionDataTask = session.dataTaskWithURL(plainURL!, completionHandler: firstHandler)

plainTask.resume()

Solution

  • HTTP Requests are not supported in "normal" iOS Playground:

    From Xcode release notes:

    iOS Playgrounds now support displaying animated views with the XCPShowView() XCPlayground API. This capability is disabled by default; it can be enabled by checking the "Run in Full Simulator" setting in the Playground Settings inspector.

    When the capability is enabled, running the playground causes the iOS Simulator application to launch and run the playground in the full simulator. This capability is also required for other functionality that fails without the full simulator, such as NSURLConnection http requests. Running in the full iOS Simulator is slower than running in the default mode. (18282806)

    Try with "Run in Full Simulator" mode, or OS X Playground. It will success.

    To display the inspector: option + command + 1 or View > Utilities > Show File Inspector from the menu.