0

I have big image it came from Api then how to load it fast . It Take too much time to load

  let data = NSData(contentsOf: NSURL(string: self.imageFile)! as URL)

            if data == nil{
            }

            else{

                DispatchQueue.main.async() {
        self.imageShow.image = UIImage(data: data! as Data)
                }
            }

this is my code can any one suggest me

Paulw11
  • 108,386
  • 14
  • 159
  • 186
Anurag Mishra
  • 109
  • 1
  • 9
  • 8
    **Never ever** load data synchronously from a remote `URL` with `Data(contentsOf`. Use asynchronous `URLSession` or similar API. And don't use `NSURL / NSData` in Swift 3+ – vadian Apr 10 '18 at 08:57
  • use SDWebImage library for loading images even big and can cache it too. – MRizwan33 Apr 10 '18 at 08:57
  • Comments/answers saying about thread - it's not yet clear if code running on main thread, maybe it's already running asynchronously, if no, then you have to change it. Also things like `NSURL(string: self.imageFile)!` are very dangerous, you should learn basic stuff like optionals, networking. – Injectios Apr 10 '18 at 09:06

2 Answers2

2

You can use this code to Async Download Image.

    if let url = self.imageFile{

    let url = URL(string: self.imageFile)

        let task = URLSession.shared.dataTask(with: url!) { data, response, error in
            guard let data = data, error == nil else { return }

            /**CHECK 404 HERE*/
            if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 400 {
                    //YOUR CODE HERE
                return
                }
            }


            DispatchQueue.main.async() {    // execute on main thread
                self.imageShow.image = UIImage(data: data)
            }
        }

    task.resume()

    }else{

        DispatchQueue.main.async() {    // execute on main thread
         self.viewImageType.isHidden = true
        }
    }

BETTER NOT TO DEPEND ON THIRD PARTY LIBRARIES

Dheeraj D
  • 4,386
  • 4
  • 20
  • 34
1

You can use NSOperationQueue to load your image on background thread and then load image on image view on main thread. You can achieve this by:

    let myQueue = OperationQueue()
    myQueue.addOperation { // Load image on background thread
        if let urlString = URL(string: self.imageFile) {
            do {
                let data = try Data(contentsOf: urlString)
                DispatchQueue.main.async { // Load image on main thread
                    self.imageShow.image = UIImage(data: data)
                }
            } catch {
                print("not able to load image")
            }
        }
    }
Ankit Jayaswal
  • 5,549
  • 3
  • 16
  • 36