在Swift 4上NSURLSession/NSURLConnection HTTP加载失败

You*_*uSS 7 xcode uiwebview nsurlconnection ios swift

我有swift 4的xcode 9.1,我无法使用webview进行身份验证.这是我的代码:

import UIKit

protocol AuthViewControllerDelegate{
    func getAccessToken(_ code: String)
}

class AuthViewController: UIViewController, NSURLConnectionDelegate {


    @IBOutlet weak var navItem: UINavigationItem!
    @IBOutlet weak var webView: UIWebView!

    var delegate: AuthViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        var link: "https://home.nest.com/login/oauth2?client_id=…"

        if let encodeURL = link.URLEncodedString(), let url = URL(string: encodeURL) {
            webView.loadRequest(URLRequest(url: url))
        }
    }


    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .lightContent
    }

    @IBAction func CancelPressed(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true, completion: nil)
    }

    func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if let url = request.url?.absoluteString, url.contains("code=") {
            if let code = getQueryStringParameter(url,param: "code"){
                self.dismiss(animated: true, completion: { () -> Void in
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false
                    self.delegate?.getAccessToken(code)
                })
            }
        }
        return true
    }

    func webViewDidStartLoad(_ webView: UIWebView){
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    func webViewDidFinishLoad(_ webView: UIWebView){
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }

    func getQueryStringParameter(_ url: String?, param: String) -> String? {
        if let url = url, let urlComponents = URLComponents(string: url), let queryItems = (urlComponents.queryItems) {
            return queryItems.filter({ (item) in item.name == param }).first?.value!
        }
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在日志中得到的错误:

2017-11-07 20:49:30.836087 + 0000 TestApp [1851:1259046] TIC TCP Conn失败[32:0x1c0365280]:3:-9800 Err(-9800)

2017-11-07 20:49:30.836472 + 0000 TestApp [1851:1259046] NSURLSession/NSURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9800)

2017-11-07 20:49:30.836578 + 0000 TestApp [1851:1259046]任务<0A675AA1-7110-4FCC-99B2-054380D22F01>.<0> HTTP加载失败(错误代码:-1200 [3:-9800])

2017-11-07 20:49:30.837548 + 0000 TestApp [1851:1258708] NSURLConnection完成错误 - 代码-1200

我已经把它放到了我的.plist文件中:

<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
Run Code Online (Sandbox Code Playgroud)

注意:相同的代码与swift 3.2完美配合

小智 1

添加NSAllowsArbitraryLoads到 .plist 文件可以解决错误

NSURLConnection 错误 - 代码 - 1200

我的开发语言是 Objective C。