swift中的HTTP请求无法正常工作

use*_*270 12 api ios nsurlsession swift

我正在尝试学习在Swift中使用API​​.作为一个很好的第一次测试,我想我已经点击itunes API并返回一些搜索结果.我在游乐场使用以下代码.我没有任何错误,但我的println没有输出任何东西.谁知道什么是错的?

谢谢!

import UIKit
import XCPlayground

XCPSetExecutionShouldContinueIndefinitely()


let url = NSURL(string: "https://itunes.apple.com/lookup?id=909253")

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

task.resume()
Run Code Online (Sandbox Code Playgroud)

小智 26

尝试添加以下代码行:

URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
Run Code Online (Sandbox Code Playgroud)


pva*_*len 21

对于Swift 3/Xcode 8.2.1,结合几个答案(rv1331,Wouter van Zuilen)给出了最好的结果,Playground中没有错误.我正在使用这个Swift 3 REST示例:

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)
Run Code Online (Sandbox Code Playgroud)


小智 11

Swift 3代码:

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

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Run Code Online (Sandbox Code Playgroud)


Jas*_*min 5

尝试以下行,我猜它会工作:

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Run Code Online (Sandbox Code Playgroud)


Nat*_*ook 0

不知道为什么你没有看到错误\xe2\x80\x94我得到这个:

\n\n

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

\n\n

您可以使用 httpbin.org\xe2\x80\x94 更有效地进行测试,这对我来说非常有用:

\n\n
let url = NSURL(string: "http://httpbin.org/get")\n\nlet task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in\n    println(NSString(data: data, encoding: NSUTF8StringEncoding))\n}\n\ntask.resume()\n
Run Code Online (Sandbox Code Playgroud)\n