从API调用更新UILabel的延迟

时间:2016-10-05 18:36:07

标签: swift multithreading uilabel nsurlsession nsoperationqueue

我正在通过API调用更新我的UILabels。我有一个API客户端文件,它提取所需的信息,然后将其传递给DataStore,然后解析信息,然后创建电影对象。 collectionViewController可以毫无问题地访问信息,但是当它将信息传递给下一个视图控制器时,就会出现问题。信息不会出现在视图控制器上,然后当我单击后面的信息时会出现。来自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)
        }

    }

//详细视图控制器 覆盖func 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")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

NSURLSession.sharedSession().dataTaskWithRequest(request)

我不确定sharedSession使用什么回调队列,如果它不是你需要的主线程

DispatchQueue.main.async {
   completion(descriptiveDictionary)
}