【问题标题】:Translating Obj-C blocks into Swift for AFNetworking calls将 Obj-C 块转换为 Swift 以进行 AFNetworking 调用
【发布时间】:2016-12-05 21:19:39
【问题描述】:

我正在尝试在 Swift 文档中使用 AFNetworking(这是必要的约束,否则我很想学习 AlamoFire)。作为一个对 Swift 很陌生的人,我正在为在这里做什么而苦苦挣扎:

- (nullable AFHTTPRequestOperation *)GET:(NSString *)URLString
                     parameters:(nullable id)parameters
                        success:(nullable void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                        failure:(nullable void (^)(AFHTTPRequestOperation * __nullable operation, NSError *error))failure;

特别是,我不清楚如何处理故障块。这是我的尝试:

manager.GET(
"random_url",
parameters: [...random parameters...],
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
        print("there was an error")
}
)

我的failure 块出现错误:

Cannot convert value of type '() -> ()' to expected argument type '((AFHttpRequestOperation?, NSError) -> Void)?'

如果人们能告诉我上面哪里出错了,我将不胜感激。非常感谢。

【问题讨论】:

  • @PEEJWEEJ 你看我的信息了吗?这个选择不在我的控制范围内。

标签: swift afnetworking objective-c-blocks


【解决方案1】:

我知道从错误中并不清楚,但是在将我们的 Swift 2 应用程序移植到 Swift 3 时,我遇到了类似的问题。问题,至少对我们来说,是关于闭包中的参数。将它们指定为可选类型,而不是强制展开的可选项。换句话说,试试:

failure: { (operation: AFHTTPRequestOperation?, error: NSError?) in
    print("there was an error")
}

同样,错误似乎并不表明这是问题所在,但这正是我们三个月前遇到的问题。

【讨论】:

  • 非常感谢!这正是问题所在。
  • 很高兴它有帮助!我知道当我们处理这个问题时是多么令人沮丧。
【解决方案2】:

看来你错过了“in”:

failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
        print("there was an error")
}

【讨论】:

  • 感谢您的建议。我进行了代码更正,但错误消息保持不变,即使在代码清理之后也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多