我正在尝试为 http get 请求编写一个协议(protocol)并在我的 View Controller 中使用它。思路是防止在每个VC中写request,在app中写一次。我编写了一个带有 get 函数的协议(protocol),并为其编写了一个扩展,以使用 Alamofire 实现 get 请求。
protocol Irequest
{
func getRequest(url: String, completion: (JSON) -> ())
func postRequest(url: String, param: Parameters, completion: (JSON) -> ())
}
extension Irequest
{
func getRequest(url: String, completion:@escaping (JSON) -> ())
{
Alamofire.request(url.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!, method: .post)
.responseJSON { response in
debugPrint(response)
if let Json = response.result.value
{
let j = JSON(Json)
completion(j)
}
else
{
completion(JSON("{}"))
}
}
}
}
现在,当我想在类里面使用它时,它说 X 类不符合协议(protocol) Irequest。我该如何使用它?更笼统地说,我怎样才能在所有应用程序中拥有一个获取请求功能?
class X : UIViewController , Irequest
最佳答案
1. 协议(protocol)的 get 方法签名是 != 扩展的 get 签名。一个没有@escaping,一个有。
==> 方法不匹配,因此 get 不存在
2。 帖子根本没有实现
==> 缺少 ergo 方法
根据你已经知道的评论 2 所以修复 1 你应该是好的 :)
关于ios - 在所有应用程序中写一次获取请求 - swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43715524/