Alamofire 4从“(_) throws ->()”类型的抛出函数到非抛出函数类型“(DataResponse <Any>)-> Void”的无效转换

Posted

技术标签:

【中文标题】Alamofire 4从“(_) throws ->()”类型的抛出函数到非抛出函数类型“(DataResponse <Any>)-> Void”的无效转换【英文标题】:Alamofire 4 Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(DataResponse<Any>) -> Void' 【发布时间】:2018-07-31 15:01:49 【问题描述】:

我刚刚运行了 pod update 命令。并在我的 Alamofire 请求的 .responseJSON response in 块中收到此错误。

'(_) throws -> ()' 类型的抛出函数的无效转换 到非抛出函数类型 '(DataResponse) -> Void'

这是截图

更新 1

这是我的代码

Alamofire.request(getPublicKeyUrl!, method: .get, parameters: nil, encoding: JSONEncoding.default)
                            .downloadProgress(queue: DispatchQueue.global(qos: .utility))  progress in
                                print("Progress: \(progress.fractionCompleted)")
                            
                            .validate  request, response, data in
                                // Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary)
                                //print("response", response);
                                return .success
                            
                            .responseJSON  response in
                                //debugPrint(response)
                                //print("JSON req", response)

                                if((response.result.value) != nil) 

                                    let swiftyJSON = JSON(response.result.value!)

                                    print(swiftyJSON)

                                    let Code = swiftyJSON["LL"]["Code"].stringValue
                                    print("response Code", Code);
                                    if (Code == "200") 

                                        // get key
                                        self._publicKey = swiftyJSON["LL"]["value"].stringValue
                                        print("publicKey", self._publicKey);

                                        var request = URLRequest(url: (URL(string:"ws://\(self._ip)/ws/rfc6455"))!)
                                        print("Request", String(describing: request.url))
                                        request.setValue("websocket", forHTTPHeaderField: "Upgrade")
                                        request.setValue("Upgrade", forHTTPHeaderField: "Connection")
                                        request.setValue("remotecontrol", forHTTPHeaderField: "Sec-WebSocket-Protocol")
                                        request.setValue(self._hash as String, forHTTPHeaderField: "Sec-WebSocket-Key")
                                        self.socket = WebSocket(request: request)

//                                        self.commandInPending.insert("authenticate/\(self._hash)", at: 0)
//                                        self.socket.delegate = self
//                                        self.socket.connect()

                                        // check AES encryption
                                        //let message     = "Don´t try to read this text. Top Secret Stuff"
                                        //let messageData = message.data(using:String.Encoding.utf8)!
                                        let keyData     = "12345678901234567890123456789012".data(using:String.Encoding.utf8)!
                                        let ivData      = "abcdefghijklmnop".data(using:String.Encoding.utf8)!

                                        print("keyData", keyData);
                                        print("ivData", ivData);

                                        let key = keyData.map String(format:"%02x", $0) .joined()
                                        let iv = ivData.map String(format:"%02x", $0) .joined()

                                        print("keyHex", key);
                                        print("ivData", iv);

                                        // let session_key =
                                        let keyAndiv = ("\(key):\(iv)") // self._publicKey
                                        print("keyAndiv", keyAndiv);

//                                        let str = "Clear Text"
                                        let clear = try ClearMessage(string: keyAndiv, using: .utf8)
                                        let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)

                                        let data = encrypted.data
                                        let base64String = encrypted.base64Encoded
                                        print ("data", data);
                                        print ("base64String", base64String);


                                        //let encryptedData = AppUtils.testCrypt(data:messageData,   keyData:keyData, ivData:ivData, operation:kCCEncrypt)
                                        //let decryptedData = AppUtils.testCrypt(data:encryptedData, keyData:keyData, ivData:ivData, operation:kCCDecrypt)
                                        //let decrypted     = String(bytes:decryptedData, encoding:String.Encoding.utf8)!

                                        //print("message", message);
                                        //print("decrypted", decrypted);

                                    
                                
                        

有什么线索吗?

【问题讨论】:

请贴代码而不是图片,这样我们可以清楚地理解。但问题是因为您在 responseJSON 完成处理程序中调用了一个抛出函数。查看WebSocket Library 和SwiftyJSON,看看你是否使用过任何投掷函数。没有您的代码,我无法提供进一步的帮助 @PranavKasetti 抱歉耽搁了。上面添加的代码。谢谢 【参考方案1】:

发生错误是因为您没有处理throwing 函数的错误。

添加do - catch block

do 
     let clear = try ClearMessage(string: keyAndiv, using: .utf8)
     let encrypted = try clear.encrypted(with: publicKey, padding: .PKCS1)

     let data = encrypted.data
     let base64String = encrypted.base64Encoded
     print ("data", data);
     print ("base64String", base64String)
 catch  print(error) 

这是 Swift,if 条件和尾随分号不需要括号

if response.result.value != nil  ...

或更好

guard let result = response.result.value else  return 
let swiftyJSON = JSON(result)

【讨论】:

以上是关于Alamofire 4从“(_) throws ->()”类型的抛出函数到非抛出函数类型“(DataResponse <Any>)-> Void”的无效转换的主要内容,如果未能解决你的问题,请参考以下文章

从 '(_, _, _) throws -> ()' 类型的抛出函数到非抛出函数类型 '(URLResponse?, Data?, Error?) -> Void 的无效转换

从 '(_) throws -> ()' 类型的抛出函数到非抛出函数类型 '(DataSnapshot) -> Void' 的无效转换

从 '(_) throws -> Void' 类型的抛出函数到非抛出函数类型 '([UNNotificationRequest]) -> Void 的无效转换

在 Swift 3.0 (Alamofire 4.4.0) 中的一些请求后,Alamofire 停止工作

无法使用类型为“(NSMutableURLRequest,(_,_,_) throws -> _)”的参数列表调用“dataTaskWithRequest”

AlamoFire 4.0 + SwiftyJSON 展开深度嵌套的 JSON