简单的URLSession示例始终失败并显示错误

时间:2018-02-16 14:21:45

标签: swift macos urlsession

我的macOS应用程序正在使用一个简单的函数,它应该建立与服务器的连接,但无论我尝试什么,我都无法使它工作。

我从其他网站复制了一个示例,但它不起作用。我还看了其他的例子,但大多数都很老了,过时了。 这是我的代码:

func connect(){

        // Set up the URL request
        let todoEndpoint: String = "https://www.google.com"
        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
            // do stuff with response, data & error here
            print(error as Any)
            print(response as Any)
        })
        task.resume()

    }

我收到以下错误

dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:11 Err:-1 Errno:1 Operation not permitted
2018-02-16 15:02:19.437098+0100 [4869:445869] [] nw_resolver_create_dns_service_locked DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2018-02-16 15:02:19.437839+0100 [4869:445869] TIC TCP Conn Failed [1:0x604000166d80]: 10:-72000 Err(-65563)
2018-02-16 15:02:19.451077+0100 [4869:445860] Task <29B127C0-8865-4AF4-8960-C1F892824A3C>.<1> HTTP load failed (error code: -1003 [10:-72000])
2018-02-16 15:02:19.451289+0100 [4869:445860] Task <29B127C0-8865-4AF4-8960-C1F892824A3C>.<1> finished with error - code: -1003
Optional(Error Domain=NSURLErrorDomain Code=-1003 "Es wurde kein Server mit dem angegebenen Hostnamen gefunden." UserInfo={NSUnderlyingError=0x60400024be80 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=-72000, _kCFStreamErrorDomainKey=10}}, NSErrorFailingURLStringKey=https://www.google.com/, NSErrorFailingURLKey=https://www.google.com/, _kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, NSLocalizedDescription=Es wurde kein Server mit dem angegebenen Hostnamen gefunden.})

我做错了什么。本地化描述说:主机无法找到,但显然不是这样。任何帮助,我高度赞赏。

1 个答案:

答案 0 :(得分:5)

问题与Outgoing connections有关,请务必在App Sandbox面板中启用此类标记:

enter image description here