2017-04-14 1 views
0

je veux afficher un indicateur d'activité à l'écran pendant que l'image est téléchargée à partir d'un site Web puis montrer dans les images.image c'est mon code ci-dessous. chaque fois que je télécharge l'image, j'imprime le statut tout de suite et l'indicateur d'activité n'apparaît jamais. été à la recherche à travers le web, mais je ne comprenais toujours pas. s'il vous plaît aidercréer un chargement d'image/indicateur d'activité, jusqu'à ce que l'image est affichée à l'écran dans swift

let mygroup = DispatchGroup() 
var activityIndicator = UIActivityIndicatorView() 

func downloadpic(sender:UIButton){ 
    let catPictureURL = URL(string: addr)! 

    // Creating a session object with the default configuration. 
    // You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration 
    let session = URLSession(configuration: .default) 

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data. 

    let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in 
     // The download has finished. 
     if let e = error { 
      print("Error downloading cat picture: \(e)") 
     } else { 
      // No errors found. 
      // It would be weird if we didn't have a response, so check for that too. 
      if let res = response as? HTTPURLResponse { 
       // put loading screen here 
       self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white) 
       self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46) 
       self.activityIndicator.startAnimating() 
       self.mygroup.enter() 
       print("downloading image") 
       print("Downloaded cat picture with response code \(res.statusCode)") 
       if let imageData = data { 
        // Finally convert that Data into an image and do what you wish with it. 
        self.images.image = UIImage(data: imageData) 
         self.mygroup.leave() 
         print("image already downloaded") 
         self.activityIndicator.stopAnimating() 
         self.activityIndicator.hidesWhenStopped = true 


        // Do something with your image. 
       } else { 
        print("Couldn't get image: Image is nil") 
       } 
      } else { 
       print("Couldn't get response code for some reason") 
      } 
     } 
    } 

    downloadPicTask.resume() 
} 

Répondre

1

Vous avez obtenu ce problème, parce que:

  1. Vous n'avez pas ajouté le activityIndicator à des vues
  2. Vous avez configuré le activityIndicator dans le completionHandler bloc

Let configurer dans le activityIndicator la méthode viewDidLoad():

self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) 
self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46) 
self.activityIndicator.hidesWhenStopped = true 

view.addSubview(self.activityIndicator) 

Et commencer à animer avant de reprendre la dataTask

self.activityIndicator.startAnimating() 

Ensuite, arrêtez-vous dans le completionHandler

self.activityIndicator.stopAnimating() 

Le code final:

let mygroup = DispatchGroup() 
var activityIndicator = UIActivityIndicatorView() 

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) 
    self.activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46) 
    self.activityIndicator.hidesWhenStopped = true 

    view.addSubview(self.activityIndicator) 
} 

func downloadpic(sender: UIButton) { 
    let catPictureURL = URL(string: addr)! 

    // Creating a session object with the default configuration. 
    // You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration 
    let session = URLSession(configuration: .default) 

    // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data. 

    self.activityIndicator.startAnimating() 

    let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in 
     // The download has finished. 
     if let e = error { 
      print("Error downloading cat picture: \(e)") 
     } else { 
      // No errors found. 
      // It would be weird if we didn't have a response, so check for that too. 
      if let res = response as? HTTPURLResponse { 
       // put loading screen here 

       self.mygroup.enter() 
       print("downloading image") 
       print("Downloaded cat picture with response code \(res.statusCode)") 
       if let imageData = data { 
        // Finally convert that Data into an image and do what you wish with it. 
        self.images.image = UIImage(data: imageData) 
        self.mygroup.leave() 
        print("image already downloaded") 
        self.activityIndicator.stopAnimating() 

        // Do something with your image. 
       } else { 
        print("Couldn't get image: Image is nil") 
       } 
      } else { 
       print("Couldn't get response code for some reason") 
      } 
     } 
    } 

    downloadPicTask.resume() 
} 

Le résultat!

enter image description here

+0

i ont déjà indicateur d'activité en vue a la charge i na pas inclus au-dessus, parce que le problème est que l'indicateur d'activité commence alors immédiatement arrêter. ce que j'essaie de faire est de montrer l'indicateur d'activité pendant que l'image est encore en train d'être téléchargée. J'ai besoin de faire en sorte que l'indicateur d'activité commence lorsque l'application télécharge l'image, puis s'arrête après l'image sont affichés dans les images. image –

+0

Regardez mon fichier joint! Je pense que c'est ce que tu veux. –

+0

vous avez raison, désolé mon erreur. et merci pour la réponse. –