【问题标题】:AlamoFire POST request is giving me an error using SwiftAlamoFire POST 请求使用 Swift 给我一个错误
【发布时间】:2019-12-15 18:59:45
【问题描述】:

我已成功调用此函数,以便在我的应用中向用户发送推送通知。我的后端是 firebase,我正在使用 Xcode。出于某种原因,从今天开始,它开始抛出错误。我是 AF 新手,所以我很困惑该怎么做。我已经在 SO 中搜索了答案,但之前的问题都没有可靠的答案。请大家帮忙,谢谢。

这里是函数

func sendPushNotification(device: String){

    let title = "Hey check this out"
    let body = "They're waiting on your response"

    let toDeviceID = device
    var headers: HTTPHeaders = HTTPHeaders()

    headers = ["content_type":"application/json", "Authorization":"key=\(AppDelegate.SERVER_KEY)"]

    let notification = ["to":"\(toDeviceID)", "notification":["body":body, "title":title, "badge":1, "sound":"default"]] as [String:Any]

    AF.request(AppDelegate.NOTIFICATION_URL as URLConvertible, method: .post as HTTPMethod, parameters: notification, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        print(response)

    }
}

我得到的错误是,

失败(Alamofire.AFError.responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误:错误域 = NSCocoaErrorDomain 代码 = 3840“字符 0 周围的值无效。” UserInfo = {NSDebugDescription = 字符周围的值无效0.})))

【问题讨论】:

  • 这个错误意味着你得到的响应不是一个有效的 JSON。尝试使用responseData { (data) in 而不是responseJSON { (response) in 并打印print(String(data: data, encoding: .utf8)) 以查看实际响应。
  • @Kamran 感谢您的回复,将立即尝试并通知您
  • @Kamran - 这是我收到的响应 - ("Error=DeprecatedEndpoint")
  • 所以你需要更新这个url中使用的endPointAppDelegate.NOTIFICATION_URL。您可能需要查看文档才能获得新的端点。
  • @Kamran,它更容易使用responseString 而不是responseData,因为使用 responseString 您不需要编码为字符串,只需在.responseString { (response) in 之后使用print(response)

标签: ios json swift apple-push-notifications alamofire


【解决方案1】:

按照@kamran 的指示 - 问题是 Firebase 端点已被替换。如果将来有人遇到此问题,请务必查看 firebase 文档。

有问题的端点 = https://gcm-http.googleapis.com/gcm/send

已解决的端点 = https://fcm.googleapis.com/fcm/send

再一次 - 这是使用 Firebase 云消息发送推送通知

【讨论】:

  • 如果您可以使用有问题的新端点更新您的答案,以便新读者轻松解决问题,那就更好了。
  • @Kamran 现在就可以了
猜你喜欢
  • 2020-02-10
  • 2018-04-10
  • 1970-01-01
  • 2015-11-23
  • 2016-02-23
  • 1970-01-01
  • 2016-11-25
  • 2020-11-09
  • 2015-11-18
相关资源
最近更新 更多