Wednesday, October 14, 2015

Open an internet image and create a button with underline title

Update: July 12, 2017 - Xcode 8.3.3 + Swift 3.1

Original Post: Xcode 6.4 (Swift 1.2)

Note: For Xcode 7 (Swift 2), refer to the information at the bottom of this page.


How to open an image file online with an iOS app?
Simply modify ViewController.swift as below:

Update: July 12, 2017 - Xcode 8.3.3 + Swift 3.1

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //--------------------- Image ----------------------
        // URL for the web image
        let url = URL(string: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKqwWN6ru5rEMD7sT38QiCuFETD-65Hizt8k7KiS5QnWfRwydKcsX0rj6zgAezKFRm-GWGjJWBHWjoa7pKy5ubbBtAECVwmuohkBx4zL9eK6_XP-UbtXjCcpPl9cFKsScIOtzWoN0pxD4/s1600/IMG_4809.JPG")
        let imageView = UIImageView(frame: CGRect(x: 20, y: 100, width: view.bounds.width-40, height: view.bounds.height-200))
        
        //Image data for Swift 3
        var data : Data!
        do {
            data = try Data(contentsOf: url!)
        } catch {
            print(error.localizedDescription)
            return
        }
        
        imageView.image = UIImage(data: data)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.scaleAspectFit
        
        view.addSubview(imageView)
        
        
        //--------------------- Link Button ----------------------
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
        
        //Relocate the button with the center position.
        button.center = CGPoint(x: view.bounds.width/2, y: 50)
        
        //Underline the button and set the text as blue.
        let attributedString = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor.blue])
        button.setAttributedTitle(attributedString, for: UIControlState.normal)
        
        //Set the highlight color as cyan.
        let attributedStringHighlight = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSForegroundColorAttributeName: UIColor.cyan])
        button.setAttributedTitle(attributedStringHighlight, for: UIControlState.highlighted)
        
        button.addTarget(self, action: #selector(btnPressed), for: UIControlEvents.touchUpInside)
        view.addSubview(button)
        
    }
    
    func btnPressed() {
        let string = "http://cutecorners.blogspot.com/"
        UIApplication.shared.open(URL(string: string)!, options: [:], completionHandler: nil)//Open the URL in the browser.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Xcode 6.4 (Swift 1.2): Edit ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //--------------------- Image ----------------------
        // URL for the web image
        let url = NSURL(string: "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiKqwWN6ru5rEMD7sT38QiCuFETD-65Hizt8k7KiS5QnWfRwydKcsX0rj6zgAezKFRm-GWGjJWBHWjoa7pKy5ubbBtAECVwmuohkBx4zL9eK6_XP-UbtXjCcpPl9cFKsScIOtzWoN0pxD4/s1600/IMG_4809.JPG")
        
        let imageView = UIImageView(frame: CGRectMake(20, 100, view.bounds.width-40, view.bounds.height-200))
        imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        
        view.addSubview(imageView)
        
        
        //--------------------- Link Button ----------------------
        let button = UIButton(frame: CGRectMake(0, 0, 200, 20))
        
        //Relocate the button with the center position.
        button.center = CGPoint(x: view.bounds.width/2, y: 50)
        
        //Underline the button and set the text as blue.
        let attributedString = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSForegroundColorAttributeName: UIColor.blueColor()])
        button.setAttributedTitle(attributedString, forState: UIControlState.Normal)
        
        //Set the highlight color as cyan.
        let attributedStringHighlight = NSAttributedString(string: "More Photos", attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue, NSForegroundColorAttributeName: UIColor.cyanColor()])
        button.setAttributedTitle(attributedStringHighlight, forState: UIControlState.Highlighted)

        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(button)
        
    }
    
    func btnPressed(sender: UIButton) {
        let string = "http://cutecorners.blogspot.com/"
        UIApplication.sharedApplication().openURL(NSURL(string: string)!)//Open the URL in the browser.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

The result:





Updated Oct. 31, 2015:  Xcode 7 (Swift 2)


While building the above code, error happens:


App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

This is because Apple has introduced App Transport Security (ATS) in iOS9, but the image link used in this example is an insecure HTTP URL. To allow this network connection, modify Info.plist by adding:



If you need secure HTTPS connections, do not use this solution. More details regarding ATS is here:


Related Information:

Apple will require HTTPS connections for iOS apps by the end of 2016

No comments:

Post a Comment