H5如何访问ios本地图片

import UIKit

class NSLocalImageURLProtocol: URLProtocol {

    static let schemaName = "myapp"

    override class func canInit(with request: URLRequest) -> Bool {
        if let schema = request.url?.scheme?.lowercased(),
            schema == schemaName {
            return true
        }
        return false
    }

    override class func canonicalRequest(for request: URLRequest) -> URLRequest {
        return request
    }

    fileprivate func getMimeString(from path: String) -> String {
        switch path.tt_extName().lowercased() {
        /// jpg
        case "jpeg":
            fallthrough
        case "jpg":
            return "imgae/jpg"
        /// png
        case "pnz":
            fallthrough
        case "png":
            return "image/png"
        /// gif
        case "gif":
            return "image/gif"
        default:
            return "image/jpg"
        }
    }

    override func startLoading() {
        if let requestUrl = request.url {

            let filePath = requestUrl.absoluteString.tt_replace("\(LocalImageURLProtocol.schemaName)://", replacement: "")

            let response = URLResponse(url: requestUrl,
                                       mimeType: getMimeString(from: filePath),
                                       expectedContentLength: -1,
                                       textEncodingName: nil)

            if let data = try? Data(contentsOf: URL(fileURLWithPath: TTFileUtils.pathAddSandbox(path: filePath))) {
                client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
                client?.urlProtocol(self, didLoad: data)
            }

        }

        client?.urlProtocolDidFinishLoading(self)
    }

    override func stopLoading() {
    }
}

由于沙箱限制,UIWebview中的H5是不能直接用"file://path"来访问本地文件的,可以用一个自定义的protocol来完成。

另外,为了安全起见,我们给H5的路径,并没有包含沙箱。

还需要webview注册一下:

/// viewdidload中
[NSURLProtocol registerClass:[NSLocalImageURLProtocol class]];

然后再H5调用的时候:

<img src="myapp:///Library/Caches/xxxxpath" />

本文实现参考自:http://stackoverflow.com/questions/5572258/ios-webview-remote-html-with-local-image-files

Leave a Reply

Your email address will not be published. Required fields are marked *