Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 云功能post请求未正确向IOS应用发送错误消息_Swift_Http_Post_Google Cloud Functions_Urlsession - Fatal编程技术网

Swift 云功能post请求未正确向IOS应用发送错误消息

Swift 云功能post请求未正确向IOS应用发送错误消息,swift,http,post,google-cloud-functions,urlsession,Swift,Http,Post,Google Cloud Functions,Urlsession,我有一个iOS应用程序从谷歌云函数接收json数据 数据被检索出来,在没有错误的情况下工作正常 但是,当云函数返回错误时,下面的函数将错误识别为nil 客户端: func initialize() { var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forH

我有一个iOS应用程序从谷歌云函数接收json数据

数据被检索出来,在没有错误的情况下工作正常

但是,当云函数返回错误时,下面的函数将错误识别为nil

客户端:

func initialize() {

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: json)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
            
            guard let response = response as? HTTPURLResponse,
                response.statusCode == 200,
                let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
                let clientSecret = json["clientSecret"] as? String,
                let publishableKey = json["publishableKey"] as? String else {
                
                ///////////   
               //ERROR is not being recognized
                /////////

           let message = error?.localizedDescription ?? "Failed to decode response from server."
           print("Error loading page: \(message)")
                    return
       }
})
task.resume()
}
firebase.functions().httpsCallable('myFunction')(message)
    .then(result => {
    // this works perfectly and is recognized by the swift function //
    res.send({publishableKey: publishableKey, clientSecret: clientSecret});
})
.catch(err => {
    // this is not recognized by the swift function //
     console.log(err) // full of data
    return res.status(400).send({error: err});
});
客户端输出:

func initialize() {

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: json)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
            
            guard let response = response as? HTTPURLResponse,
                response.statusCode == 200,
                let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
                let clientSecret = json["clientSecret"] as? String,
                let publishableKey = json["publishableKey"] as? String else {
                
                ///////////   
               //ERROR is not being recognized
                /////////

           let message = error?.localizedDescription ?? "Failed to decode response from server."
           print("Error loading page: \(message)")
                    return
       }
})
task.resume()
}
firebase.functions().httpsCallable('myFunction')(message)
    .then(result => {
    // this works perfectly and is recognized by the swift function //
    res.send({publishableKey: publishableKey, clientSecret: clientSecret});
})
.catch(err => {
    // this is not recognized by the swift function //
     console.log(err) // full of data
    return res.status(400).send({error: err});
});
无法解码来自服务器的响应

服务器:

func initialize() {

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: json)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
            
            guard let response = response as? HTTPURLResponse,
                response.statusCode == 200,
                let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
                let clientSecret = json["clientSecret"] as? String,
                let publishableKey = json["publishableKey"] as? String else {
                
                ///////////   
               //ERROR is not being recognized
                /////////

           let message = error?.localizedDescription ?? "Failed to decode response from server."
           print("Error loading page: \(message)")
                    return
       }
})
task.resume()
}
firebase.functions().httpsCallable('myFunction')(message)
    .then(result => {
    // this works perfectly and is recognized by the swift function //
    res.send({publishableKey: publishableKey, clientSecret: clientSecret});
})
.catch(err => {
    // this is not recognized by the swift function //
     console.log(err) // full of data
    return res.status(400).send({error: err});
});
日志(用于错误情况):

func initialize() {

        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try? JSONSerialization.data(withJSONObject: json)
        let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
            
            guard let response = response as? HTTPURLResponse,
                response.statusCode == 200,
                let data = data,
                let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
                let clientSecret = json["clientSecret"] as? String,
                let publishableKey = json["publishableKey"] as? String else {
                
                ///////////   
               //ERROR is not being recognized
                /////////

           let message = error?.localizedDescription ?? "Failed to decode response from server."
           print("Error loading page: \(message)")
                    return
       }
})
task.resume()
}
firebase.functions().httpsCallable('myFunction')(message)
    .then(result => {
    // this works perfectly and is recognized by the swift function //
    res.send({publishableKey: publishableKey, clientSecret: clientSecret});
})
.catch(err => {
    // this is not recognized by the swift function //
     console.log(err) // full of data
    return res.status(400).send({error: err});
});
函数执行耗时240毫秒,完成状态代码:400


如果您的请求失败,我认为您的错误将进入响应参数,您必须对其进行解码。我认为只有当服务器无法访问或函数不存在时,error参数才会不同于nil。因此,基本上在else子句中,您必须搜索response参数以查找错误。

那么您的说法是从cloud函数发送一个JSON对象,每个case success和error都使用相同的参数?我想我给每个json对象添加了错误,如果没有错误,就用nil填充。我想客户端是在将“return res.status(400).send({error:err});”解释为响应,而不是错误。它将进入else子句,因为它无法解码json[“clientSecret”]和json[“publishableKey”]好的,让我测试一下。我觉得你是对的。