ios - 使用 Alamofire 和不记名 token 序列化对象

标签 ios json xcode swift alamofire

在 IOS 8、Xcode 6.3 和 swift 项目中使用优秀的 Alamofire 库 v1.2,我试图从 JSON-API 响应序列化对象,我想知道哪种方法是完成它的最佳方法。 我认为下面代码中的主要问题是:

  • 在类 Controller 中,println(data) 显示为 nil。
  • 在俱乐部对象中 类、位置属性未正确映射。

JSON-API 响应是:

hits = [{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVip" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVip" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

通用响应集合序列化:

@objc public protocol ResponseCollectionSerializable {
    static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}

extension Alamofire.Request {
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self {
        let serializer: Serializer = { (request, response, data) in
            let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
            if response != nil && JSON != nil {
                return (T.collection(response: response!, representation: JSON!), nil)
            } else {
                return (nil, serializationError)
            }
        }

        return response(serializer: serializer, completionHandler: { (request, response, object, error) in
            completionHandler(request, response, object as? [T], error)
        })
    }
}

俱乐部对象类

final class Club: ResponseCollectionSerializable {

    @objc static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Club] {
        var clubs = [Club]()

        if let representation = representation as? [[String: AnyObject]] {
            for representationValue in representation {
                let club = Club(JSON: representationValue)
                clubs.append(club)
            }
        }

        return clubs
    }

    let id: String
    let name: String
    let imageUrl: String
    let hasVip: Bool
    let location: String

    init(JSON: AnyObject) {
        id = JSON.valueForKeyPath("id") as! String
        name = JSON.valueForKeyPath("name") as! String
        imageUrl = JSON.valueForKeyPath("imageUrl") as! String
        hasVip = JSON.valueForKeyPath("hasVip") as! Bool

        //is OK this implementation?
        location = JSON.valueForKeyPath("location") as! String
    }
}

View Controller 类

class ClubsViewController: UIViewController, UITableViewDataSource{

    var results: [JSON]? = []
    var clubs: [Club]?

    @IBOutlet var tableview:UITableView!



    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadClubsObjects()
    }

    func loadClubsObjects(){


        var URL = NSURL(string: "https://api.com/v1/clubs")
        var mutableURLRequest = NSMutableURLRequest(URL: URL!)
        mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded")
        mutableURLRequest.HTTPMethod = "GET"
        mutableURLRequest.setValue("Bearer R01.iNsG3xjv/r1LDkhkGOANPv53xqUFDkPM0en5LIDxx875fBjdUZLn1jtUlKVJqVjsNwDe1Oqu2WuzjpaYbiWWhw==", forHTTPHeaderField: "Authorization")
        let manager = Alamofire.Manager.sharedInstance
        let request = manager.request(mutableURLRequest)
        request.responseCollection { (request, response, clubs: [Club]?, error) in

        println("request = \(request)")
        println("response = \(response)")
        println("clubs = \(clubs)")
        println("error = \(error)")

            if (json != nil){
                var jsonObj = JSON(json!)
                if let data = jsonObj["hits"].arrayValue as [JSON]? {
                    self.results = data
                    self.tableview.reloadData()

                }
            }
        }



    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.results?.count ?? 0
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("clubsObjectCell") as! ClubsTableViewCell
        cell.clubsObject = self.results?[indexPath.row]
        return cell    }

}

println(clu​​bs) 的输出是:

   request = <NSMutableURLRequest: 0x7fd553725870> { URL: https://api.com/v1/clubs }
response = Optional(<NSHTTPURLResponse: 0x7fd553439e20> { URL: https://api.com/v1/clubs } { status code: 200, headers {
    "Access-Control-Allow-Headers" = "X-Requested-With, Accept, Origin, Referer, User-Agent, Content-Type, Authorization";
    "Access-Control-Allow-Methods" = "GET,PUT,POST,DELETE,OPTIONS";
    "Access-Control-Allow-Origin" = "*";
    Connection = "keep-alive";
    "Content-Encoding" = gzip;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Tue, 21 Apr 2015 20:18:07 GMT";
    Etag = "W/\"sEDn5KBhpfpInjAtNsF4gQ==\"";
    Server = "nginx/1.6.2";
    "Transfer-Encoding" = Identity;
    Vary = "Accept-Encoding";
    "X-Powered-By" = Express;
} })
clubs = Optional([])
error = nil

最佳答案

为了确定一下,您可以将 ViewController 类中的最后几行更改为以下内容吗?

request.responseJSON { request, response, json, error in
    println(request)
    println(response)
    println(json)
    println(error)
}

我想确保您已正确设置请求并得到您期望的响应。这当然是成功的一半。一旦您可以验证这一点,我们就可以处理 responseCollection 解析逻辑。

另外,您使用的是哪个版本的 Xcode 以及哪个版本的 Alamofire?


更新

您遇到的问题有两个方面。

问题 1

首先,您没有正确调用 responseCollection 方法。您应该按如下方式调用它:

request.responseCollection { request, response, clubs: [Club], error in
    println("request = \(request)")
    println("response = \(response)")
    println("clubs = \(clubs)")
    println("error = \(error)")
}

这将正确调用您的 Club 类。

问题 2

第二个问题是您没有在 Club 对象中实现 collection 方法。如果不实际迭代该集合,您永远不会获得任何俱乐部。大致如下所示的内容应该会让您朝着正确的方向前进。

final class Club: ResponseCollectionSerializable {
    @objc static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Club] {
        var clubs = [Club]()

        if let representation = representation as? [[String: AnyObject]] {
            for representationValue in representation {
                let club = Club(JSON: representationValue)
                clubs.append(club)
            }
        }

        return clubs
    }

    let id: String
    let name: String
    let imageUrl: String
    let hasVip: Bool

    init(JSON: AnyObject) {
        id = JSON.valueForKeyPath("id") as! String
        name = JSON.valueForKeyPath("name") as! String
        imageUrl = JSON.valueForKeyPath("imageUrl") as! String
        hasVip = JSON.valueForKeyPath("hasVip") as! Bool
    }
}

一旦您的 collection 函数实际上迭代了 JSON 数组中的所有表示值,您应该会更幸运。

奖励积分

对于奖励积分,这里有一些其他技巧可以改进您的代码。

  • 切换到在 Club 类中使用可失败的初始值设定项,以保证仅在成功解析 JSON 时才创建对象
  • 更改 responseCollection 完成闭包内的实现,以实际存储新的俱乐部值并在表格 View 中显示这些俱乐部。

The object returned to the responseCollection closure is no longer a JSON AnyObject that you can use with SwiftyJSON, but instead an array of Clubs.

关于ios - 使用 Alamofire 和不记名 token 序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29735949/

相关文章:

java - 使用 GSON 库获取 JSON 对象/数组,无需转换为 pojo

java - 我需要从列表标签内的 json 脚本获取数据

ios - 如何通过 ScrollView 将 admobs 放入 xcode 4.6

ios - 在不同的机器上构建时是否仍然需要导出开发者配置文件?

ios - 无法使用类型为 '*' 的参数列表调用 '($9 floatLiteralConvertible)'

java - Javascript JNI 覆盖类型中 Long 的 GWT 问题

ios - 如何使用 SwiftyJSON 解析特定格式的 json?

objective-c - 应用程序在 i386 上崩溃,在 x86_64 上工作

ios - 访问 GCDAsyncSocket 读取队列

ios - 如何手动调用RxSwift注册的手势识别器?