环境
- macOS High Sierra 10.13.6
- X Code 9.4.1
- Swift 4.1
操作
- 创建URLSession
- 创建URLSessionTask
- 捕获Response
- 执行Task
1 | let url = URL(string: "https//www.baidu.com") //创建url |
1 | // 状态码判断 |
可能出现的问题
http协议的请求无法访问 The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
编辑 info.plist
文件
Information Property List
点击 + , 添加 App Transport Security Settings
,点击 +
添加子属性 Allow Arbitrary Loads
设置值为 YES
无法连接到网络/找不到 dns A server with the specified hostname could not be found.
错误日志:
nw_resolver_create_dns_service_locked DNSServiceCreateDelegateConnection failed:
NSErrorFailingURLStringKey=http://www.baidu.com/, NSErrorFailingURLKey=http://www.baidu.com/, _kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, NSLocalizedDescription=A server with the specified hostname could not be found.}
点击项目左侧导航栏中的项目名称,右侧顶部标签选择 Capabilities
找到第一项 NetWork
勾选 Incoming Connections (Server)
和 Outgoing Connections (Client)
或者干脆直接把App SandBox关了
总结
Swift 相关的信息网上比较少,尤其在百度环境下,基本上没找到任何有用的信息,全都是无用的复制粘贴帖子,而且 Swift版本已经更新至 4, 很多方法已经过时或被删除或类名修改。遇到问题最好还是去 Google,Stack Overflow 。
网上的教程可以作为参考,本文中的代码在以后的版本也许不适用,所以使用还得借助官方的文档,文档可以在官网或 X Code 中找到 ( Shift + Command + 0 / Help - Developer Documentation)