Swift 3 HTTP请求无法通过

时间:2016-10-27 01:36:18

标签: swift

我正在尝试学习Swift和网络。我正在向www.google.com发送简单的HTTP请求,但它似乎没有执行。这是我写的代码

let url = URL(string: "www.google.com")
var request = URLRequest(url: url!)
let task =  URLSession.shared.dataTask(with: request) { data, response, error in
        print(response)
    }

这似乎没有执行。我已经在线查看并且没有Swift 3的帮助。如何在swift 3中发出HTTP请求?我做错了什么?

2 个答案:

答案 0 :(得分:0)

您忘记了task.resume()

let url = URL(string: "http://www.google.com:80/")
var request = URLRequest(url: url!)
let task =  URLSession.shared.dataTask(with: request) { data, response, error in
    print(response)
}
task.resume()

哦和https://http://

这是我整个游乐场。

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

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let url = URL(string: "http://www.google.com:80/")
var request = URLRequest(url: url!)
let task =  URLSession.shared.dataTask(with: request) { data, response, error in
    print(response)
}
task.resume()

更新以显示如何使用端口。

答案 1 :(得分:0)

您忘记了task.resume(),但您可能也忘记添加应用传输安全域例外,因此如果您还没有,请将其添加到Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>google.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>