为什么第一个completionHandler在调用所有方法之前返回数据?

时间:2017-01-27 13:48:38

标签: ios swift3 alamofire completionhandler

这是我的API代码

import UIKit
import Alamofire
import SwiftyJSON

class ItunesApi: NSObject
{
var artistArray:Array <Artist> = []

func downloadData(name:String, _ completionHandler:   @escaping (_ result: Array<Artist>) -> Void)
{
    Alamofire.request("https://itunes.apple.com/search?term=U2&entity=musicArtist").response
        { response in

        if let data = response.data
        {
           let JsonResult = JSON(data)
           self.findDiscography(data: JsonResult)

        }
        completionHandler(self.artistArray)
      }

}

func findDiscography (data: JSON)
    {
        for (subJson):(String, JSON) in data["results"]
        {
            if let artistName = subJson.1["artistName"].string
            {
                print(artistName);
                self.downloadDiscography(name: artistName)
            }
        }
    }

func downloadDiscography (name: String)
{
    Alamofire.request("https://itunes.apple.com/search?term=U2&entity=album").response
        { response in
            if let data = response.data
            {
                let JsonResult = JSON(data)
                self.createDataModel(name: name, data: JsonResult)
            }

    }
}



func createDataModel (name: String, data: JSON)
{
    var albums:Array <Album> = []
    for (subJson):(String, JSON) in data["results"]
    {
        var thumbnail:String = ""
        var title:String = ""
        var year:String = ""

        if let thumbImage = subJson.1["artworkUrl60"].string
        {
            thumbnail = thumbImage;
        }
        if let titleString = subJson.1["collectionName"].string
        {
            title = titleString;
        }
        if let releaseDate = subJson.1["releaseDate"].string
        {
            year = releaseDate;
        }
        let album = Album(_thumbnail: thumbnail, _title: title, _year: year)
        albums.append(album)
    }
    let artist = Artist(_name: name, _musicStyle: "Rock", _albums: albums as NSArray);
    self.artistArray.append(artist);
}

}

我在MyClassTableView.m

中调用此处
func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
{
     if let artist = searchBar.text
     {
       self.itunesApi.downloadData(name: artist, { (array) in
            print(array);
       })
     }
}

为什么copmletionHandler在调用所有方法之前返回?我想在第一个completionHandeler中返回所有方法的结果,但它之前返回。 self.itunesApi.dow​​nloadData返回[]而不是数组填充

0 个答案:

没有答案