1

I am downloading an html page which looks like this from a local Jetty 9 server.

<h1>Hello</h1>
<img src="tiles/tile00.jpg">
<img src="tiles/tile01.jpg">

When I navigate to that page in Chrome, my server receives requests for

/
/tiles/tile00.jpg
/tiles/tile01.jpg
/favicon.ico

and the page displays with the images in Chrome.

However when I navigate to that page using the Swift code below, I only receive a request for

/

and the text renders, but the images only render as [?] icons.

@IBAction func displayWebPage(sender: UIButton) {
    let h2Url = NSURL(string: "https://localhost:8443")!
    let downloadDelegate = Deleg(view: self)
    let ses = NSURLSession(
        configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
        delegate: downloadDelegate,
        delegateQueue: nil
    )
    ses.downloadTaskWithURL(myUrl).resume()
}
func completed(location: NSURL) {
    print("downloaded")
    var htmlString = "NON, MERCÍ"
    do {
        htmlString = try String.init(
            contentsOfURL: location,
            encoding: NSUTF8StringEncoding
        )
    } catch {
        print("ERRORED OUT")
        fatalError()
    }
    print("contents: \(htmlString)")
    self.webView.loadHTMLString(htmlString, baseURL: nil)
}

class Deleg: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {
    var view: ViewController
    init(view: ViewController) {
        self.view = view
    }
    func URLSession(
        session: NSURLSession,
        downloadTask: NSURLSessionDownloadTask,
        didFinishDownloadingToURL location: NSURL
    ) {
        self.view.completed(location)
    }
}

Is there a way to convince the NSURLSession to download the assets linked-to in the html page that it downloads?

One solution would be to use let the UIWebView download the linked assets, but then I would not be able to use self-signed certificates.

EthanP
  • 1,663
  • 3
  • 22
  • 27
  • 1
    You may try using a XML/HTML parse to extract these links then use NSURLSession to download them. You can use NSXMLParser, or if you are familiar with XPath or CSS selector, you may try this library: https://github.com/cezheng/Fuzi – cezheng Nov 27 '15 at 13:34
  • OK thanks I will try that. I need to get the NSURLSession to reuse the TCP connection(s) to simulate what a real browser would do. I think that will be possible though. – EthanP Nov 27 '15 at 20:53

0 Answers0