0

Я обновляю свои UILabels из вызова API. У меня есть файл API-клиента, который извлекает необходимую информацию, а затем передает ее в DataStore, а затем анализирует информацию и затем создает объекты фильма. CollectionViewController обращается к информации без проблем, но когда она передает информацию на следующий контроллер представления, возникает проблема. Информация не появляется на контроллере представления, а затем, когда я нажимаю на нее, появится информация. Существует некоторая задержка в информации от клиента API или что-то, что я не могу понять.Задержка при обновлении UILabel из вызова API

//Second API call to get information for the Second View Controller (Detail View Controller) 
    class func getDescriptiveMovieResultsFromSearch(movieID: String, completion:(NSDictionary)->()) 
    { 
     var descriptiveDictionary: [String: String] = [:] 

     let searchURL = "https://www.omdbapi.com/?i=\(movieID)&?plot=short" 

     let nsurl = NSURL(string: searchURL) 
     //convert the url into an NSURL 

     guard let unwrappedNSURL = nsurl else {print("ERROR OCCURRED HERE"); return} 
     //unwrap the nsurl using guard let 

     //let session = NSURLSession.sharedSession() 

     let request = NSMutableURLRequest(URL: unwrappedNSURL) 
     //creation of the request 

     request.HTTPMethod = "GET" 
     //By Default everythiing is a GET request if you are getting information and you don't need it 
     //request has an HTTPMethod of type "GET" to obtain information 

     let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in 

      guard let unwrappedData = data else {print("Error occurred here"); return} 

      if let responseDictionary = try? NSJSONSerialization.JSONObjectWithData(unwrappedData, options: []) as? NSDictionary 
      { 
       let castedResponseDictionary = responseDictionary as? [String : String] 

       guard let unwrappedResponseDictionary = castedResponseDictionary else {print("This did not work!"); return} 

       descriptiveDictionary = unwrappedResponseDictionary 

      } 
      completion(descriptiveDictionary) 
    } 
     task.resume() 
    } 

//MovieDataStore function to parse through the information 
/Second API Call 
    func getDescriptiveMovieInformationWith(movie: Movie, Completion: (Bool) ->()) 
    { 
     guard let unwrappedimdbID = movie.imdbID else {print("AN ERROR OCCURRED HERE"); return} 
     OMDBAPIClient.getDescriptiveMovieResultsFromSearch(unwrappedimdbID) { (descriptiveResponseDictionary) in 

      let desMovieDirector = descriptiveResponseDictionary["Director"] as? String 
      let desMovieWriters = descriptiveResponseDictionary["Writer"] as? String 
      let desMovieActors = descriptiveResponseDictionary["Actors"] as? String 
      let desMovieShortPlot = descriptiveResponseDictionary["Plot"] as? String 
      let desMovieimbdRating = descriptiveResponseDictionary["imdbRating"] as? String 

      //unwrapping each of the of the json information 
      guard let 
       unwrappedDesMovieDirector = desMovieDirector, 
       unwrappedDesMovieWriters = desMovieWriters, 
       unwrappedDesMovieActors = desMovieActors, 
       unwrappedDesMovieShortPlot = desMovieShortPlot, 
       unwrappedDesMovieimbdRating = desMovieimbdRating 

       else {print("AN ERROR OCCURRED HERE!"); return} 

       movie.director = unwrappedDesMovieDirector 
       movie.writers = unwrappedDesMovieWriters 
       movie.actors = unwrappedDesMovieActors 
       movie.shortPlot = unwrappedDesMovieShortPlot 
       movie.imdbRating = unwrappedDesMovieimbdRating 

       print("******************************************") 
       print("Movie Director: \(movie.director)") 
       print("Movie writers: \(movie.writers)") 
       print("Movie actors: \(movie.actors)") 
       print("Movie shortPlot: \(movie.shortPlot)") 
       print("Movie imdbRating: \(movie.imdbRating)") 
       print("******************************************") 
      //Completion(true) 
      Completion(true) 
     } 

    } 

//Detail View Controller 
/Second API Call 
    func getDescriptiveMovieInformationWith(movie: Movie, Completion: (Bool) ->()) 
    { 
     guard let unwrappedimdbID = movie.imdbID else {print("AN ERROR OCCURRED HERE"); return} 
     OMDBAPIClient.getDescriptiveMovieResultsFromSearch(unwrappedimdbID) { (descriptiveResponseDictionary) in 

      let desMovieDirector = descriptiveResponseDictionary["Director"] as? String 
      let desMovieWriters = descriptiveResponseDictionary["Writer"] as? String 
      let desMovieActors = descriptiveResponseDictionary["Actors"] as? String 
      let desMovieShortPlot = descriptiveResponseDictionary["Plot"] as? String 
      let desMovieimbdRating = descriptiveResponseDictionary["imdbRating"] as? String 

      //unwrapping each of the of the json information 
      guard let 
       unwrappedDesMovieDirector = desMovieDirector, 
       unwrappedDesMovieWriters = desMovieWriters, 
       unwrappedDesMovieActors = desMovieActors, 
       unwrappedDesMovieShortPlot = desMovieShortPlot, 
       unwrappedDesMovieimbdRating = desMovieimbdRating 

       else {print("AN ERROR OCCURRED HERE!"); return} 

       movie.director = unwrappedDesMovieDirector 
       movie.writers = unwrappedDesMovieWriters 
       movie.actors = unwrappedDesMovieActors 
       movie.shortPlot = unwrappedDesMovieShortPlot 
       movie.imdbRating = unwrappedDesMovieimbdRating 

       print("******************************************") 
       print("Movie Director: \(movie.director)") 
       print("Movie writers: \(movie.writers)") 
       print("Movie actors: \(movie.actors)") 
       print("Movie shortPlot: \(movie.shortPlot)") 
       print("Movie imdbRating: \(movie.imdbRating)") 
       print("******************************************") 
      //Completion(true) 
      Completion(true) 
     } 

    } 

// детальный вид контроллера переопределение функ viewDidLoad() {

super.viewDidLoad() 

    self.view.backgroundColor = UIColor.blackColor() 
    self.titleLabel.textColor = UIColor.yellowColor() 
    self.yearLabel.textColor = UIColor.yellowColor() 
    self.directorLabel.textColor = UIColor.yellowColor() 
    self.writersLabel.textColor = UIColor.yellowColor() 
    self.actorsLabel.textColor = UIColor.yellowColor() 
    self.shortPlotLabel.textColor = UIColor.yellowColor() 
    self.imdbIDLabel.textColor = UIColor.yellowColor() 
    self.typeLabel.textColor = UIColor.yellowColor() 
    self.imdbRating.textColor = UIColor.yellowColor() 

    stackViewLabel.translatesAutoresizingMaskIntoConstraints = false 
    stackViewLabel.topAnchor.constraintEqualToAnchor(self.topImage.bottomAnchor, constant: 5).active = true 
    stackViewLabel.widthAnchor.constraintEqualToAnchor(self.view.widthAnchor, multiplier: 1.00).active = true 
    stackViewLabel.heightAnchor.constraintEqualToAnchor(self.view.heightAnchor, multiplier: 0.50).active = true 
    stackViewLabel.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true 

    //unwrapped Movie Object 
    guard let unwrappedMovieObject = movieObject else {print("AN ERROR OCCURRED HERE!"); return} 

    self.store.getDescriptiveMovieInformationWith(unwrappedMovieObject) { (isWorking) in 
     if isWorking { 

     dispatch_async(dispatch_get_main_queue()){ 
      guard let unwrappedPosterURL = unwrappedMovieObject.posterURL else {print("AN ERROR OCCURRED HERE"); return} 
      if unwrappedPosterURL == "N/A"{ 
      self.topImage.image = UIImage.init(named: "star_PNG1592") 
      } 
      else { 
       if let url = NSURL(string: unwrappedPosterURL){ 
        if let data = NSData(contentsOfURL: url){ 
         //print("I have an image to display") 
         self.topImage.image = UIImage.init(data: data) 
         } 
        } 
       } 
       self.titleLabel.text = unwrappedMovieObject.title 
       self.yearLabel.text = unwrappedMovieObject.year 
       self.imdbIDLabel.text = unwrappedMovieObject.imdbID 
       self.typeLabel.text = unwrappedMovieObject.type 

       guard let 
        unwrappedDirector = unwrappedMovieObject.director, 
        unwrappedWriters = unwrappedMovieObject.writers, 
        unwrappedActors = unwrappedMovieObject.actors, 
        unwrappedShortPlot = unwrappedMovieObject.shortPlot, 
        unwrappedRating = unwrappedMovieObject.imdbRating 

       else {print("PROPERTIES WERE UNWRAPPED"); return} 

        self.directorLabel.text = unwrappedDirector 
        self.writersLabel.text = unwrappedWriters 
        self.actorsLabel.text = unwrappedActors 
        self.shortPlotLabel.text = unwrappedShortPlot 
        self.imdbRating.text = unwrappedRating 
      } 
     } 

     else{ 

      print("AN ERROR OCCURRED HERE") 
     } 
    } 
} 
+0

Это контроллер подробного просмотра, используя информацию из DataStore для обновления UIL abel –

+0

Поблагодарили бы за вход! Благодаря! –

+0

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

ответ

0
NSURLSession.sharedSession().dataTaskWithRequest(request) 

Я не уверен, что обратный вызов очереди использует sharedSession, если его не основная нить вам нужно будет до

DispatchQueue.main.async { 
    completion(descriptiveDictionary) 
} 
+0

Проблема в этом, если пусть responseDictionary = try? NSJSONSerialization.JSONObjectWithData (unwrappedData, options: []) as? NSDictionary, и это должно было быть разрешено responseDictionary = попробовать? NSJonsSerialization.JSONObjectWithData (unwrappedData, options: []) as! NSdicitonary –