Downloading Images From The Web

Code to download images from the Web and save them to the iPhone.

//
//  ViewController.swift
//  Download Images from the Web
//
//  Created by Dmitriy Baranoff on 25/05/2019.
//  Copyright © 2019 freedevelopers.org. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var image: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // restore image
        
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        //  .userDomainMask - the user’s home directory—the place to install user’s personal items (~).
        
        
        if documentPath.count > 0 {
            let documentsDirectory = documentPath[0]
            let restorePath = documentsDirectory + "/tiger.jpg"
            image.image = UIImage(contentsOfFile: restorePath)
        }
        
        
        // save image,  uncomment before restore image from path and comment after
        
        /*
        guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/b/b9/P.t.altaica_Tomak_Male.jpg") else {
            return
        }
        let request = NSMutableURLRequest(url: url)
        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in
            
            if let error = error {
                print(error)
            } else {
                guard let data = data else {
                    return
                }
                if let tigerImage = UIImage(data: data) {
                    self.image.image = tigerImage
                    
                    let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
                    
                    if documentPath.count > 0 {
                        let documentsDirectory = documentPath[0]
                        let savePath = documentsDirectory + "/tiger.jpg"
                        do {
                            try tigerImage.jpegData(compressionQuality: 1)?.write(to: URL(fileURLWithPath: savePath))
                            
                        } catch {
                            print("Error")
                        }
                    }
                }
            }
            
        }
        
        task.resume()
 */
    }


}

Join the Discussion

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

Back to top