Swift - 使用闭包在init方法中设置属性

时间:2016-04-16 22:10:04

标签: ios swift api

我正在访问Web API以访问某些JSON并初始化GRDMovie对象。在这种情况下,我需要使用其他URL的其他属性来访问API。这导致了GRDMovie init方法中的一些问题,因为关闭被忽略了。代码如下:

var posterImage : UIImage?
let title : String
let score : Double
var rating : String?
let releaseDate : String
let overview : String
let movieID : Int
let smallURL : String
let year : String

init(title:String, overview:String, score:Double, movieID:Int, releaseDate:String, smallURL: String, year:String) {

    self.title = title
    self.overview = overview
    self.score = score
    self.movieID = movieID
    self.releaseDate = releaseDate
    self.smallURL = smallURL
    self.year = year
    self.rating = nil
    self.posterImage = nil


    self.getMovieRatingWith(movieID) { (rating) in
        self.rating = rating
    }

    self.getPosterImageDataFromURL(smallURL) { (posterImage) in
        self.posterImage = posterImage
    }
}

func getMovieRatingWith(movieID: Int, completion: (rating: String) -> ()) {

    var apiDict = NSDictionary()
    var rating: String = ""

    let urlString:String = "http://api.themoviedb.org/3/movie/\(movieID)?api_key=ebea8cfca72fdff8d2624ad7bbf78e4c&append_to_response=releases"
    let escapedUrlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
    let apiURL = NSURL(string:escapedUrlString!)
    let session = NSURLSession.sharedSession()

    session.dataTaskWithURL(apiURL!, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) in
        do {
            if let data2 = data {
                let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                //send json outward
                apiDict = jsonDict

                if let releases = apiDict["releases"] as? NSDictionary {
                    if let countries = releases["countries"] as? [NSDictionary] {
                        for countryData in countries {
                            if let place: String = countryData["iso_3166_1"] as? String {
                                if place == "US" {
                                    rating = countryData["certification"] as! String
                                } else {

                                }
                            }
                        }
                    }
                }

                if rating == "" {
                    rating = "Not Available"
                }

                completion(rating: rating)
                //print(rating)
            }
        } catch {
            //handle NSError
            print("error")
        }
    }).resume()
}

func getPosterImageDataFromURL(smallURL:String, completion: (posterImage: UIImage) -> ()) {

    let escapedURLString:String = smallURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    let callURL = NSURL(string: escapedURLString)
    let session = NSURLSession.sharedSession()

    session.dataTaskWithURL(callURL!) { (data:NSData?, response:NSURLResponse?, error:NSError?) in
        do {
            if let data2 = data {
                let poster = UIImage(data: data2)
                completion(posterImage: poster!)
            }
        }
    }

}

当然,我对posterImage和评级都是零。如何构建它以正确捕获这些值?

1 个答案:

答案 0 :(得分:0)

我认为最好在控制器中进行api调用。您可以先创建一个obj,也可以在api回调取决于您想要的内容后创建它。

如果您想先创建obj,请在下面执行此操作。

在GRDMovieController.swift中(我只是随机命名):

let obj : GRDMovie?

在某处初始化obj并调用api获取数据:

obj = GRDMovie(title, overview: overview, score: score, movieID: id, releaseDate: date, smallURL: url, year: year)
getMovieRatingWith(obj)
getPosterImageDataFromURL(obj)

功能可以是这样的:

func getMovieRatingWith(movieObj: GDVMovie) {
    var apiDict = NSDictionary()
    var rating: String = ""

    let urlString:String = "http://api.themoviedb.org/3/movie/\(movieObj.movieID)?api_key=ebea8cfca72fdff8d2624ad7bbf78e4c&append_to_response=releases"
    let escapedUrlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
    let apiURL = NSURL(string:escapedUrlString!)
    let session = NSURLSession.sharedSession()

    session.dataTaskWithURL(apiURL!, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) in
        do {
            if let data2 = data {
                let jsonDict = try NSJSONSerialization.JSONObjectWithData(data2, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                //send json outward
                apiDict = jsonDict

                if let releases = apiDict["releases"] as? NSDictionary {
                    if let countries = releases["countries"] as? [NSDictionary] {
                        for countryData in countries {
                            if let place: String = countryData["iso_3166_1"] as? String {
                                if place == "US" {
                                    rating = countryData["certification"] as! String
                                } else {

                                }
                            }
                        }
                    }
                }

                if rating == "" {
                    rating = "Not Available"
                }

                movieObj.rating = rating

                //print(rating)
            }
        } catch {
            //handle NSError
            print("error")
        }
    }).resume()
}

func getPosterImageDataFromURL(movieObj: GRDMovie) {

    let escapedURLString:String = movieObj.smallURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    let callURL = NSURL(string: escapedURLString)
    let session = NSURLSession.sharedSession()

    session.dataTaskWithURL(callURL!) { (data:NSData?, response:NSURLResponse?, error:NSError?) in
        do {
            if let data2 = data {
                let poster = UIImage(data: data2)
                movieObj.posterImage = poster
            }
        }
    }

}

如果我错了,请纠正我,希望这会有所帮助。