【问题标题】:iOS 11 Loading Images from HTTP with ATSiOS 11 使用 ATS 从 HTTP 加载图像
【发布时间】:2017-09-15 20:08:29
【问题描述】:

您好,您可以使用以下代码从 Web 服务器下载图像。该请求是 HTTP,因此不安全。

 DispatchQueue.global(qos: .userInitiated).async {
        var productImage = Utilities.GetEmptyImageBottle()
        if (entry.ImageName != nil || entry.ImageUrl != nil) {
            let data = NSData(contentsOf: URL(string: entry.ImageUrl.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)!)

            if data != nil {
                let image = UIImage(data: data! as Data)
                productImage = image!
            }
        }
        DispatchQueue.main.async {
            cell.ProductImage.image = productImage
        }
    }

我还在 info.plist 中添加了以下内容

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

现在我的图片无法加载,并且出现以下错误:

NSURLConnection finished with error - code -1002

这是在运行 iOS 11 的 Xcode 9 中。在 Xcode 8 中的 iOS 10 上,没有问题。

我错过了什么?

【问题讨论】:

  • 除了问题之外,您的代码有很多问题。不要使用nil 检查,而是使用if let 语句。此外,您应该使用 NSURLSession. 异步加载 Web 请求

标签: ios swift web-services nsurl


【解决方案1】:

NSURLErrorUnsupportedURL 最可能的原因是该 URL 没有可用的协议处理程序(可能您的 URL 字符串在 URL 前缀中缺少“http://”?)。

【讨论】:

  • 问题出在这里:.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
【解决方案2】:
Error : Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" 

-1002 似乎是 URL(主机名)的问题,而不是 http。

【讨论】:

    【解决方案3】:

    我不太确定问题是由 iOS 11 还是 Xcode 9 引起的,但听起来你需要应用这个

    .addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

    仅在 URL 的最后一部分,您可能会在其中找到特殊字符。我尝试了它并且它有效,将它应用于完整的 url 将 http: 格式损坏为 http%35,这不是 url 的基础,因此不会调用 web 视图的失败事件。因此,仅将其应用于您可能怀疑它包含特殊字符如空格等的 url 部分

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-30
      • 2018-03-04
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 2011-08-05
      相关资源
      最近更新 更多