对Swift
的 协议
枚举
泛型
等有一定了解的话会很便于理解
public protocol MyServiceProtocol: SwiftyServiceProtocol where SwiftyServiceCallBackType == 你的网络库的回调 {
}
extension MyServiceProtocol {
/// 如果你的项目只有一个域名,在这里写死就好。如果不同模块有不同的域名,那么在对应的Service中实现这个get就行,测试环境生产环境的逻辑也可以放在这里
var base: String {
return "你的域名"
}
var urlString: String {
return base + "/" + path
}
func request(completion: SwiftyServiceCallBackType?) {
switch method {
case .GET:
get(completion: completion)
case .POST:
post(completion: completion)
}
}
// MARK: - Private
private func post(completion: 你的网络库的回调?) {
// 你的POST实现
}
private func get(completion: 你的网络库的回调?) {
// 你的GET实现
}
}
enum YourUserService { // 定义你需要的接口
/// 获取用户信息
case Info(uid: Int64)
/// 关注某人
case Follow(uid: Int64)
/// 取消关注某人
case UnFollow(uid: Int64)
}
extension YourUserService: MyServiceProtocol {
// var base: String {
// return "如果这个模块有不同模块有不同的域名,在这里实现这个get就行"
// }
/// 接口参数
var parameters: [AnyHashable : Any]? {
switch self {
case let .Info(uid):
return ["uid" : uid]
case .Follow(let uid):
return ["id" : uid]
case .UnFollow(let uid):
return ["id" : uid]
}
}
/// 接口路径
var path: String {
switch self {
case .Info:
return "info的path"
case .Follow:
return "follow的path"
case .UnFollow:
return "unfollow的path"
}
}
/// 请求方法选择
var method: SwiftyServiceMethod {
switch self {
case .Info:
return .GET
default:
return .POST
}
}
}
UserService
.Info(yourUser.uid)
.request { (response) in
// 处理网络回调
}