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

时间:2018-01-29 15:20:21

标签: 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证书? 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

  

作为一种解决方法,以下方法可以提供帮助

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

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

您需要像

一样导入SessionDelegate
YourController: UIViewController, URLSessionDelegate

然后实施auth挑战

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()

应该有一个auth挑战,它会自动信任它。也许它会被信任进一步调用,你会从https获得你的图像。

但就像说的那样,这可能只是一种解决方法。您需要一个值得信赖的证书。