Sunday, 26 August 2018

Asynchronous Image Loader [Swift 4] - PERFECTLY WORKING

Create a new swift file and copy paste the below class

It also store images in cache and when you load the image next time with this class it will be load quickly.


import UIKit

class ImageLoader {
    
    var cache = NSCache<AnyObject, AnyObject>()
    
    class var sharedInstance : ImageLoader {
        struct Static {
            static let instance : ImageLoader = ImageLoader()
        }
        return Static.instance
    }
    
    func imageForUrl(urlString: String, completionHandler:@escaping (_ image: UIImage?, _ url: String) -> ()) {
            let data: NSData? = self.cache.object(forKey: urlString as AnyObject) as? NSData
            
            if let goodData = data {
                let image = UIImage(data: goodData as Data)
                DispatchQueue.main.async {
                    completionHandler(image, urlString)
                }
                return
            }
        
        let downloadTask: URLSessionDataTask = URLSession.shared.dataTask(with: URL.init(string: urlString)!) { (data, response, error) in
            if error == nil {
                if data != nil {
                    let image = UIImage.init(data: data!)
                    self.cache.setObject(data! as AnyObject, forKey: urlString as AnyObject)
                    DispatchQueue.main.async {
                        completionHandler(image, urlString)
                    }
                }
            } else {
                completionHandler(nil, urlString)
            }
        }
        downloadTask.resume()
    }
}


Usage:

// Call this class for a single image or Run the below code inside a for loop and pass URL Strings in a loop to this class. Works Smoothly for both.

ImageLoader.sharedInstance.imageForUrl(urlString: "Your_Path_To_Image_URL") { (image, urlString) in

            if image != nil {

                // Set Your Image Here

            }

        }


Generate QR Code for a string [Swift 4]


func generateQRcode(from string: String) -> UIImage? {
     
        let data = string.data(using: String.Encoding.ascii)
     
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setDefaults()

            filter.setValue(data, forKey: "inputMessage")

            let transform = CGAffineTransform(scaleX: 3, y: 3)
         
            if let output = filter.outputImage?.transformed(by: transform) {
                let context:CIContext = CIContext.init(options: nil)
                let cgImage:CGImage = context.createCGImage(output, from: output.extent)!
                let rawImage:UIImage = UIImage.init(cgImage: cgImage)
             

                let cgimage: CGImage = (rawImage.cgImage)!
                let cropZone = CGRect(x: 0, y: 0, width: Int(rawImage.size.width), height: Int(rawImage.size.height))
                let cWidth: size_t  = size_t(cropZone.size.width)
                let cHeight: size_t  = size_t(cropZone.size.height)
                let bitsPerComponent: size_t = cgimage.bitsPerComponent
             
                let bytesPerRow = (cgimage.bytesPerRow) / (cgimage.width  * cWidth)
             
                let context2: CGContext = CGContext(data: nil, width: cWidth, height: cHeight, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: cgimage.bitmapInfo.rawValue)!
             
                context2.draw(cgimage, in: cropZone)
             
                let result: CGImage  = context2.makeImage()!
                let finalImage = UIImage(cgImage: result)
             
                return finalImage
             
            }
        }
     
        return nil
    }


Usage:

// It will return an image

let image = generateBarcode(from: "Type_Your_String_Here")



Read contacts in iOS using Swift with error handling

Just copy and paste the below code Pre-step before pasting the below code Add below line in AppDelegate.swift file below import statement ...