iPhone UIWebView: loadData does not work with certain types (Excel, MSWord, PPT, RTF)

后端 未结 2 804
太阳男子
太阳男子 2020-12-03 05:46

My task is to display the supported document types on an iPhone with OS 3.x, such as .pdf, .rtf, .doc, .ppt, .png, .tiff etc.

Now, I have stored these files

相关标签:
2条回答
  • 2020-12-03 06:28

    I experienced a very similar issue (i get my files from a server however) and saw your post and thought it was a dead end and then just by chance started to experiment on the device (iPad, in this instance) and it worked when i gave the baseURL as what i used to get it from the server and it worked but does not work on the simulator. I would try that, otherwise I would submit a bug report to Apple.

    0 讨论(0)
  • 2020-12-03 06:33

    Here is solution via NSURLProtocol:

    class CoreDataFileURLProtocol : NSURLProtocol {
        var connection: NSURLConnection!
    
        override class func canInitWithRequest(request: NSURLRequest) -> Bool {
            return (request.URL.scheme == "coredatafile")
        }
    
        override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
            return request
        }
    
        override func startLoading() {
            if let file_id = self.request.URL.absoluteString?.lastPathComponent {
                if let file = SAFile.MR_findFirstByAttribute("file_id", withValue: file_id) as? SAFile {
                    let response = NSURLResponse(URL: request.URL, MIMEType: file.mime, expectedContentLength: Int(file.filesize), textEncodingName: "utf-8")
                    client?.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
                    client?.URLProtocol(self, didLoadData: file.data)
                    client?.URLProtocolDidFinishLoading(self)
                }
            }
        }
    
        override func stopLoading() {
        }
    }
    

    Now you need only register class:

    NSURLProtocol.registerClass(CoreDataFileURLProtocol.self)
    

    And create a request with file_id:

    let url = NSURL(scheme: "coredatafile", host: "myapp.com", path: "/\(file.file_id)")
    webView.loadRequest(NSURLRequest(URL: url!))
    
    0 讨论(0)
提交回复
热议问题