123FLO321 123FLO321 - 7 months ago 65
Swift Question

Swift. Display image from website (xxx.?action=stream)

I want to display an image from a website. The problem is that the image is at "xxx.?action=stream"

I tried:

extension UIImageView {
public func imageFromUrl(urlString: String) {
if let url = NSURL(string: urlString)
{
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
self.image = UIImage(data: data!)
}
}
}


This works for images which have a file extension but not for the image in my case.

Website html code:

<html>
<body style="margin: 0px">
<img style="-webkit-user-select: none; display: block; margin: auto; cursor: zoom-in;" src="http://1.1.1.181:8085/?action=stream" width="627" height="353">
</body>
</html>

Answer

First, install Fuzi - or any other capable third party, I'm just using this one for the example - and import it:

import Fuzi

Download the webpage itself as data with, for example, NSURLSession.

NSURLSession.sharedSession().dataTaskWithURL(webpageURL, completionHandler: { (data, response, error) in
    if let error = error {
        print(error.debugDescription)
    } else {
        if let data = data {
            // next code takes place here
        }
    }
}).resume()

Decode the data as a String then create an instance of HTMLDocument:

do {
    if let html = String(data: data, encoding: NSUTF8StringEncoding) {
        let doc = try HTMLDocument(string: html)
        // next code takes place here
    }
} catch let error as NSError {
    print(error.debugDescription)
}

The trick is then to inspect your HTML and understand the path to what you want to target.

From your example, you need to find the img tag and then fetch its src value.

Find the tag(s):

let path = doc.css("img")

Get its src attribute:

if let firstObject = path[0] {
    let link = firstObject["src"]
    print(link)
}

Complete example:

NSURLSession.sharedSession().dataTaskWithURL(webpageURL, completionHandler: { (data, response, error) in
    if let error = error {
        print(error.debugDescription)
    } else {
        if let data = data {
            do {
                if let html = String(data: data, encoding: NSUTF8StringEncoding) {
                    let doc = try HTMLDocument(string: html)
                    let path = doc.css("img")
                    if let firstObject = path[0],
                        link = firstObject["src"] {
                        print(link)
                    }
                }
            } catch let error as NSError {
                print(error.debugDescription)
            }
        }
    }
}).resume()

With your example HTML, this prints:

http://1.1.1.181:8085/?action=stream

Now that you've got the image link, you can download the image itself.

Comments