alamofireobjectmapper requestObject无法进行正确的请求和映射

时间:2016-09-11 12:15:23

标签: json swift alamofire objectmapper

您好我在解析时遇到了问题。

当我尝试在tableviewcell中解析this JSON时 并且无法获得我需要的值。

我的要求:

    let videos = NewestVideos()
    let URL = "https://api.vid.me/channel/1/new"


    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, self.URL).responseObject { (response: Response<NewestVideos, NSError>) in

            switch response.result {
            case .Success(self.videos):
                print("")
            case .Failure(let error):
                    print("Request failed with error: \(error)")

            }
        }
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! NewTableViewCell

        cell.newVideoNameLabel.text = resultr


        return cell
    }

如何获取tableviewcell中的值,并提出正确的请求?

我通过ObjectMapper进行映射:

    class Videos: Mappable {
    var embedUrl: String?
    var title: String?

    required init?(_ map: Map){

    }
    func mapping(map: Map) {
        embedUrl <- map["embed_url"]
        title <- map["title"]

    }
}

class NewestVideos: Mappable {
    var videos: [Videos]? = []


    required init?(_ map: Map){

    }
    func mapping(map: Map) {
        videos <- map["videos"]
    }
}

1 个答案:

答案 0 :(得分:0)

你的可映射类看起来还不错,除了视频应该是视频。

class Video: Mappable {

    var embedUrl: String?
    var title: String?

    required init?(_ map: Map) {}

    func mapping(map: Map) {
        embedUrl <- map["embed_url"]
        title <- map["title"]
    }
}

class NewestVideos: Mappable {

    var videos: [Video]? = []

    required init?(_ map: Map) {}

    func mapping(map: Map) {
        videos <- map["videos"]
    }
}

接下来在您的控制器中,您正在使用switch语句做一些奇怪的事情。您应该将响应结果设为.Some,然后将self.videos设置为newest.videos

class ViewController: UIViewController, ... {

    ...

    var videos = [Video]() {
        didSet {
            tableView.reloadData()
        }
    }

    ...

    override func viewDidLoad() {

        super.viewDidLoad()

        let request = Alamofire.request(.GET, "https://api.vid.me/channel/1/new")

        request.responseObject { (response: Response<NewestVideos, NSError>) in

            switch response.result {
            case .Success(let newest):
                self.videos = newest.videos
            case .Failure(let error):
                print("Request failed with error: \(error)")
            }
        }
    }

    ...

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! NewTableViewCell
        let video = self.videos[indexPath.row]

        cell.newVideoNameLabel.text = video.name

        return cell
    }

    ...
}