Alamofire 响应处理程序的问题
Posted
技术标签:
【中文标题】Alamofire 响应处理程序的问题【英文标题】:Problems with Alamofire response handler 【发布时间】:2021-07-23 17:38:12 【问题描述】:对于我的项目,我想解析一个 Alamofire JSON 响应并将其保存在 Realm 中。我已经通过从 Mock-API 获取 JSON 进行了测试,它运行良好,但是当我尝试将我的代码合并到我的 AM 响应处理中时,我收到了这个错误:
从 '(AFDataResponse) throws -> Void' 类型的抛出函数(又名 '(DataResponse) throws -> ()')到非抛出函数类型 '(AFDataResponse) -> Void 的无效转换' (aka '(DataResponse) -> ()')
响应代码如下所示:
.responseJSON response in //this is where I'm getting the error
print(response)
self.books = [Books]()
do
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let booksFromJson = json["books"] as? [[String : AnyObject]]
for bookFromJson in booksFromJson
let book = Books()
if let title = bookFromJson["title"] as? String, let author = bookFromJson["author"] as? String, let imageLink = bookFromJson["imageLink"] as? String
book.author = author
book.title = title
book.imageLink = imageLink
self.books?.append(book)
这是我的 AM-Request 整体:
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
if let image:UIImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
self.myImage = image
AF.upload(multipartFormData: (multipartFormData) in
multipartFormData.append(self.myImage.jpegData(compressionQuality: 0.5)!, withName: "image", fileName: "image.png", mimeType: "image/jpeg")
, to: "https://booknerdvirtualreadinglist.herokuapp.com/getbook" , headers: nil )
.uploadProgress progress in
print(progress)
.responseJSON response in
print(response)
self.books = [Books]()
do
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let booksFromJson = json["books"] as? [[String : AnyObject]]
for bookFromJson in booksFromJson
let book = Books()
if let title = bookFromJson["title"] as? String, let author = bookFromJson["author"] as? String, let imageLink = bookFromJson["imageLink"] as? String
book.author = author
book.title = title
book.imageLink = imageLink
self.books?.append(book)
dismiss(animated: true, completion: nil)
提前谢谢你!
【问题讨论】:
为什么要复制?另外,如果我没记错的话,应该是:switch response case .failure(let afError): print(error); case .success(let res): if let json = res as? [String: AnyObject] //do the rest as your code
不相关但 JSON 值绝不是引用类型 (AnyObject
),它是 Any
。而.mutableContainers
在 Swift 中毫无意义,特别是如果您将结果分配给 im 可变常量。
请将您的解决方案发布在答案中,而不是问题中。谢谢。
【参考方案1】:
您没有正确捕获错误,因为您的“try catch”只有一个 do 块。
这是在 Swift 中正确处理错误的方法:
do
// some throwing code
catch
print("Failed with error \(error)")
缺少关键部分。
【讨论】:
以上是关于Alamofire 响应处理程序的问题的主要内容,如果未能解决你的问题,请参考以下文章
如何使用序列化为数据的响应数据处理程序(通过 AlamoFire 的 Swift 3)