Как добавить UIActivityIndicatorView с помощью URLSession в Swift? - PullRequest
0 голосов
/ 04 января 2019

У меня есть проект Master-Detail, где я анализирую данные из JSON.Цель состоит в том, чтобы добавить UIActivityIndicatorView (с помощью URLSession) в DetailsViewController во время ожидания получения данных и загрузки в DetailsViewController.Я попробовал несколько способов, запустив UIActivityIndicatorView в Master после следующего:

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

Также я не знаю, где это остановить, я пробовал это в ViewDidLoad () DetailViewController (до configureView ()):

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    configureView()
}

Но тоже не сработало.Я нигде не смог найти информацию о добавлении индикатора активности, используя состояние URLSession.Здесь я добавляю код из MasterViewController, где я пытался запустить индикатор активности:

let arrayOfUrls = [ URL(string: "http://www.omdbapi.com/?t=The+Dark+Knight&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Lord+of+the+Rings%3A+The+Return+of+the+King&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Forrest+Gump&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Inception&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Matrix&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Interstellar&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Pianist&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Intouchables&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Departed&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Prestige&apikey=f85dc75e") ]


    for url in arrayOfUrls {

        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

        if let error = error {
            print (error)
        } else {

            if let data = data {

                do {                        
                    let movie = try JSONDecoder().decode(Movie.self, from: data)
                    print(movie.Title)
                    self.objects.append(movie.Title)
                    self.details.append(movie)
                } catch {                        
                    print("Json Processing Failed")                        
                }
            }
        }
        }
        task.resume()
    }
}

1 Ответ

0 голосов
/ 04 января 2019

Создайте класс NetworkService и выполняйте вызовы API в функции, таким образом, гораздо лучше.

class NetworkService {

let arrayOfUrls = [ URL(string: "http://www.omdbapi.com/?t=The+Dark+Knight&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Lord+of+the+Rings%3A+The+Return+of+the+King&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Forrest+Gump&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Inception&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Matrix&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=Interstellar&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Pianist&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Intouchables&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Departed&apikey=f85dc75e"), URL(string: "http://www.omdbapi.com/?t=The+Prestige&apikey=f85dc75e") ]


func getData(completion:@escaping(Movie)->()){
    for url in arrayOfUrls {

    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
    var movie = Movie()
    if let error = error {
        print (error)
    } else {

        if let data = data {

            do {                        
                movie = try JSONDecoder().decode(Movie.self, from: data)
                print(movie.Title)
                self.objects.append(movie.Title)
                self.details.append(movie)
            } catch {                        
                print("Json Processing Failed")                        
            }
        }
    }
     completion(movie)
    }
    task.resume()
}

}

}

В поле зрения контроллера вызовите вашу функцию:

  let networkService = NetworkService()
    activityIndicator.startAnimating()
    networkService.getData { result in
    self.activityIndicator.stopAnimating()
    //result your movie data do whatever yo want it
    DispatchQueue.main.async {
    //If you need to reload tableview or etc. do here
   }
 }
...