【发布时间】:2016-06-21 15:05:24
【问题描述】:
我正在使用 Alamofire 对我的服务器进行 REST 调用,以获取、添加、更新和删除对象。我想知道的是,是否可以(并且推荐)将 Alamofire 调用包装到我自己的自定义对象(DTO)中,以便我可以简单地执行 user.delete(id) 和 user.add(newUser) 之类的操作在我的代码库中使用 Alamofire 代码?如果是这样,我该怎么做才能返回成功和失败处理程序(来自 javascript 世界的“承诺”)?像这样的:
user.add(newUser)
.success(userObject){
}
.error(response){
}
这是我当前的代码:
//register a user
let parameters = [“username”: txtUsername.text! , "password": txtPassword.text!]
Alamofire.request(.POST, “http://myserver.com/users", parameters: parameters, encoding: .JSON)
.validate()
.responseObject { (response: Response<User, NSError>) in
if let user = response.result.value {
self.user = user
}
}
}
User.swift
final class User : ResponseObjectSerializable, ResponseCollectionSerializable {
var id: Int
var firstName: String?
var lastName: String?
var email: String?
var password: String?
init?(response: NSHTTPURLResponse, representation: AnyObject) {
id = representation.valueForKeyPath("id") as! Int
firstName = representation.valueForKeyPath("first_name") as? String
lastName = representation.valueForKeyPath("last_name") as? String
email = representation.valueForKeyPath("email") as? String
password = representation.valueForKeyPath("password") as? String
}
static func collection(response response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users: [User] = []
if let representation = representation as? [[String: AnyObject]] {
for userRepresentation in representation {
if let user = User(response: response, representation: userRepresentation) {
users.append(user)
}
}
}
return users
}
//Can I wrap my alamofire calls in methods like this:
func getById(id: Int)
func getAll()
func add(user: User)
func update (user: User)
func delete(id: int)
}
【问题讨论】:
标签: ios swift swift2 alamofire