将Alamofire调用包装到Swift中的自定义对象中? [英] Wrapping Alamofire calls into custom objects in Swift?

查看:118
本文介绍了将Alamofire调用包装到Swift中的自定义对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Alamofire对我的服务器进行REST调用,以获取,添加,更新和删除对象。我想知道的是,是否可能(并建议)将Alamofire调用包装到我自己的自定义对象(DTO)中,以便我可以简单地执行诸如user.delete(id)和user.add(newUser)之类的操作在我的代码库中拥有Alamofire代码?如果是这样,我该怎么做才能返回成功和失败处理程序(JavaScript世界中的承诺)?像这样的东西:

I am using Alamofire to make REST calls to my server to get, add, update, and delete objects. What I'm wondering is, is it possible (and recommended) to wrap the Alamofire calls into my own custom objects (DTO), so that I can simply do things like user.delete(id) and user.add(newUser) instead of having Alamofire code all over my codebase? If so, how can I do it so I can return the success and failure handlers (the "promise" from the javascript world)? Something like this:

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) 

    }


推荐答案

我认为静态函数是您想要的,我为此写了一个示例:

i think a static func is what you want , i wrote a example for it :

final class User{

var valueHandle :((AnyObject) -> ())?
var errorHandle :((NSError)->())?

func success(value:(AnyObject) -> ())->Self{
    //pass success handle 
    self.valueHandle = value
    return self
}

func error(error:(NSError)->())->Self{
    //pass error handle 
    self.errorHandle = error
    return self
}

static func getById(id: Int)->User{

    return userRequest(.GET, urlString: "https://httpbin.org/get", param: ["foo": "bar"])

}

static func userRequest(method:Alamofire.Method , urlString:String ,param:[String: AnyObject]?) -> User {
    let user = User()
    Alamofire.request(method, urlString, parameters:param)
        .validate()
        .responseJSON { response in
            switch response.result {
            case .Success(let value):
                //invoke with your back userobj
                user.valueHandle?(value)
                print(value)
            case .Failure(let error):
                user.errorHandle?(error)
            }
    }
    return user
}

}

然后您可以使用:

User.getById(1)
.success { (value) in
    print("value = \(value)")
}
.error { (error) in
    print("error = \(error)")

}

希望它会有所帮助:D

hope it be helpful :D

这篇关于将Alamofire调用包装到Swift中的自定义对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆