HTTP Request in swift not working

纵饮孤独 提交于 2019-12-02 20:58:08
rv1331

Try adding this line of code:

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)

For Swift 3/Xcode 8.2.1, combining a couple of the answers (rv1331, Wouter van Zuilen) gave the best results with no errors in Playground. I'm using this Swift 3 REST example:

http://mrgott.com/swift-programing/30-work-with-rest-api-in-swift-3-and-xcode-8-using-urlsession-and-jsonserialization

import PlaygroundSupport
import Foundation

PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
Wouter van Zuilen

Swift 3 code:

<!-- language: lang-c -->

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

try following line and i guess it will work:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

Not sure why you aren't seeing an error—I get this:

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)

You can test more effectively with httpbin.org—this works perfectly for me:

let url = NSURL(string: "http://httpbin.org/get")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

My answer is not correct, it's really only the in the playgound indefinitite page execution. The session type does not matter.

Run into the same issue recently and found a solution.

The error is caused by using URLSession.shared() which apparently is not allowed in a playground sandbox.

Create and use your own ephemeral URL session instead:

let session = URLSession(configuration: URLSessionConfiguration.ephemeral)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!