Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Get Image from URL Swift 3 Tutorial – Downloading Images in Swift

July 3, 2017 by Belal Khan 4 Comments

Hey guys, welcome to another post, which is Get Image From URL Swift 3. So basically we will learn how to get image from URL in Swift 3 or we can say downloading images in Swift 3.

Get Image From URL Swift 3 Tutorial Video

  • You can also go through this video explanation.

Get Image From URL Swift 3 Tutorial

Creating a new Project

  • We will create a SingleView application again.
  • So I just created a project named ImageLoadingExample. (You can create a project with any name).

Adding UIImageView

  • Now from the right search UIImageView. It is a view that we can use to display images.

imageview

  • Drag it to your storyboard as you can see in the below image.

UIImageView Storyboard

  • Now open assistant editor and connect this view with your ViewController.swift file. If you don’t know how to do this check Xcode Button Tutorial.
  • After connection your code will be like this.
//
//  ViewController.swift
//  ImageLoadingExample
//
//  Created by Belal Khan on 03/07/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var uiImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()        
    }
}

  • Now we need an Image. So I will be using the following URL .
http://www.simplifiedtechy.net/wp-content/uploads/2017/07/simplified-techy-default.png
  • If you will go to the above URL you will see the following image. You can use any URL but it must be a valid URL.

simplified techy default

  • So we have the Image URL, now lets download the image.

Fetching Image from URL

  • Now to fetch the Image from the URL we will use the following code.
//
//  ViewController.swift
//  ImageLoadingExample
//
//  Created by Belal Khan on 03/07/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    //URL containing the image
    let URL_IMAGE = URL(string: "http://www.simplifiedtechy.net/wp-content/uploads/2017/07/simplified-techy-default.png")
    
    @IBOutlet weak var uiImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let session = URLSession(configuration: .default)
    
        //creating a dataTask
        let getImageFromUrl = session.dataTask(with: URL_IMAGE!) { (data, response, error) in

            //if there is any error
            if let e = error {
                //displaying the message
                print("Error Occurred: \(e)")
                
            } else {
                //in case of now error, checking wheather the response is nil or not
                if (response as? HTTPURLResponse) != nil {

                    //checking if the response contains an image
                    if let imageData = data {
                        
                        //getting the image
                        let image = UIImage(data: imageData)
                        
                        //displaying the image
                        self.uiImageView.image = image
                        
                    } else {
                        print("Image file is currupted")
                    }
                } else {
                    print("No response from server")
                }
            }
        }
        
        //starting the download task
        getImageFromUrl.resume()
        
    }
}

Allowing HTTP Request

  • The URL we are using here is http and be default ios only allows request on https urls. So we need to allow http URLs using info.plist file.
  • So open the info.plist file as source code.

info plist

  • Add the following xml code just before the last closing </dict> tag.
    <key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>
  • Now try running the application in simulator.

get image from url swift 3

  • As you can see it is working absolutely fine.

So thats it for this Get Image from URL Swift 3 Tutorial. Lets discuss in comments if you have any queries or feedbacks. And please SHARE this post if you found it useful. Thank You 🙂

 

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: get image from url swift 3, load image from url swift

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. nilesh sinha says

    July 5, 2017 at 5:38 am

    thankyou belal

    Reply
  2. David Collins says

    November 18, 2017 at 5:15 am

    Thanks, Belal. Another nice tutorial.

    I applied this code in a table view that had images in each cell, and I got problems with images appearing very slowly, and sometimes cells having the wrong image.

    After much research, I found the problem – the code updates the ImageView within the background thread.

    Easy fix, update it in the main thread ..

    DispatchQueue.main.async {
    //displaying the image
    self.uiImageView.image = image
    }

    Reply
  3. Quentin says

    January 21, 2018 at 10:18 am

    I was struggling with that but didn’t knew swift was blocking “non-https” image !
    Thank you very much for your help 😉

    Reply
  4. Nilesh says

    January 31, 2018 at 8:43 am

    I am trying to load image from URL which is protected with username and pass but its not downloading Image.
    What extra I need to pass or exactly I should do it. Please help.

    Reply

Leave a Reply Cancel reply

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




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,467)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,354)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (80,016)
  • Download Full High Sierra Installer to Create Bootable USB (70,346)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,312)
  • How to Format USB on Mac? Formatting External Hard… (61,392)
  • Swift JSON Tutorial – Fetching and Parsing… (59,414)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,721)
  • iOS Registration Form Example using PHP and MySQL (48,989)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,228)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·