ios - 如何在 UITextView 中显示 HTML 内容中的 https 图像?

标签 ios swift

我当前使用以下代码在 TextView 中加载 html 内容(来自 JSON WS):

if let stringHTML = contentHTML.data(using: String.Encoding.unicode, allowLossyConversion: true) {

    do {
        let attrStr = try NSMutableAttributedString(
            data: stringHTML,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil)

        attrStr.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0, attrStr.length), options: .init(rawValue: 0), using: { (value, range, stop) in
            if let attachement = value as? NSTextAttachment {
                let image = attachement.image(forBounds: attachement.bounds, textContainer: NSTextContainer(), characterIndex: range.location)!
                let screenSize: CGRect = UIScreen.main.bounds
                if image.size.width > screenSize.width-20 {
                    let newImage = image.resizeImage(scale: (screenSize.width-2)/image.size.width)
                    let newAttribut = NSTextAttachment()
                    newAttribut.image = newImage
                    attrStr.addAttribute(NSAttachmentAttributeName, value: newAttribut, range: range)
                }
            }
        })

        contentTextView.attributedText = attrStr
    } catch _ {
        contentTextView.text = ""
    }
}

这适用于 http 图像,但不适用于 https。 我已在 info.plist 中将 NSAllowsArbitraryLoads 设置为 true :

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

但不显示 https 图片。 https图片可以在浏览器中显示,但证书不受信任。如何允许不受信任的 https 证书? 有什么想法吗?

最佳答案

简而言之:您需要信任或拥有有效的证书

As a workaround this following approach could help

请勿将此代码用于生产。如果存在身份验证挑战,它只会信任任何证书。

在使用 html 之前,尝试发出请求并信任证书。

您需要像这样导入 SessionDelegate

YourController: UIViewController, URLSessionDelegate

然后实现身份验证挑战

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    print("auth challange")
    let trust = challenge.protectionSpace.serverTrust!
    let credential = URLCredential(trust: trust)
    completionHandler(.useCredential, credential)
}

然后调用您的网站

let url : NSString = "https://yourwebite.com"

let urlStr : NSString = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! as NSString
let searchURL : URL = URL(string: urlStr as String)!

let request = NSMutableURLRequest(url: searchURL, cachePolicy: NSMutableURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 300)

let session = URLSession(configuration: URLSession.shared.configuration, delegate: self, delegateQueue: OperationQueue.main)

let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in

})

task.resume()

应该出现一个身份验证挑战,它会自动信任它。也许它也会被信任以进行进一步的调用,并且您将从 https 获取图像。

但正如所说,这可能只是一种解决方法。您需要一个受信任的证书。

关于ios - 如何在 UITextView 中显示 HTML 内容中的 https 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504527/

相关文章:

ios - 将 .otf 字体添加到 iphone 应用程序

objective-c - 苹果手机 : responder chain in UIScrollView

iphone - 以编程方式组合 UITabController 和 UINavigation Controller http ://t. co/R52RlUL UITabController 和 UINavigation Controller 以编程方式

ios - 设置 UITextField 的光标位置不起作用(快速)

iOS - AudioKit 在接听电话时崩溃

ios - UITableView 和 UIView 手势冲突

ios - 如何在 ios 中获取 GCM 通知

ios - 在 NSUserDefaults 中存储类并在下一个 View 中访问

core-data - swift 1.2 覆盖 NSManagedObject 扩展中的prepareForDeletion

swift - 使用 Realm 集合和合并时在哪里调用 freeze()?