从Swift 3.0打开网址

时间:2019-03-01 12:57:01

标签: ios swift xcode url

我正在用Swift 3.0构建一个应用程序,当用户单击UIButton时,我想打开一个URL。

URL像这样:“ 192.169.1.19/RELE-3”

因此,我正在构建以下代码:

func sendHttpRequest(endPoint : String){
        let url = URL(string: endPoint)!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "GET"
        /*let parameters: [String: Any] = [
        "id": 13,
        "name": "Jack & Jill"
        ]*/
        //request.httpBody = parameters.percentEscaped().data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data,
            let response = response as? HTTPURLResponse,
            error == nil else {                                              // check for fundamental networking error
                print("error", error ?? "Unknown error")
                return
            }

            guard (200 ... 299) ~= response.statusCode else {                    // check for http errors
                print("statusCode should be 2xx, but is \(response.statusCode)")
                print("response = \(response)")
                return
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
            }

        task.resume()
    }

如果我尝试启动应用程序并调用此函数,则没有任何错误,但未调用页面。

1 个答案:

答案 0 :(得分:-1)

可能是ATS问题。 打开Plist作为源代码formate,然后在下面的代码中添加。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>192.169.1.19</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
    <key>NSAllowsLocalNetworking</key>
    <true/>
</dict>

添加键值为true的允许任意载荷可以解决,但不建议这样做。