Я пытаюсь переписать свою рабочую функцию для отправки уведомлений на Alatofire 5, но я сталкиваюсь с ошибкой (Alamofire.AFError.responseValidationFailed (причина: Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode (код: 400))
Это рабочая функция:
func sendMessage(token: String) {
let urlString = "https://fcm.googleapis.com/fcm/send"
let url = NSURL(string: urlString)!
let paramString: [String : Any] = ["to": token,
"priority": "high",
"notification": ["title": "test", "body": "test", "sound": "default", "badge": 1],
"data": ["user": "test_id"]
]
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("key=xxxxxxxxxxx", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
NSLog("Received data:\n\(jsonDataDict))")
}
}
} catch let err as NSError {
print(err.debugDescription)
}
}
task.resume()
}
Это моя попытка переписать ее на Alamofire 5
func sendMessage(token: String) {
let parameters: [String: Any] = [
"to": token,
"priority": "high",
"notification": [
"title": "test",
"body": "test",
"sound": "default",
"badge": 1
],
"data": [
"user": "test_id"
]
]
let headers: HTTPHeaders = [
.contentType("application/json"),
.authorization("key=xxxxxxxxxx")
]
AF.request("https://fcm.googleapis.com/fcm/send", method: .post, parameters: parameters, headers: headers)
.validate()
.responseJSON { response in
debugPrint(response)
}
}
Также прикрепите выходные данные debugPrint:
[Request]: POST https://fcm.googleapis.com/fcm/send
[Request Body]:
data%5Buser%5D=test_id¬ification%5Bbadge%5D=0¬ification%5Btitle%5D=%D0%9B%D0%B8%D1%81%D0%B8%D0%BD%20%D0%94%D0%BC%D0%B8%D1%82%D1%80%D0%B8%D0%B9¬ification%5Bsound%5D=default¬ification%5Bbody%5D=Dsds&priority=high&to=cReH043tXk9boQTZuNxOGF%3AAPA91bG_SitwV7niS5IY5tPxDeD1Juczw3pwy36MumzuGfhV9onKFIo744Bf0_pHQPKWvRaNoG9za3drXr6KLxU0oYJX
[Response]:
[Status Code]: 400
[Headers]:
Cache-Control: private, max-age=0
Content-Encoding: gzip
Content-Length: 78
Content-Type: text/plain; charset=UTF-8
Date: Mon, 23 Mar 2020 04:18:11 GMT
Expires: Mon, 23 Mar 2020 04:18:11 GMT
Server: GSE
alt-svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,h3-T050=":443"; ma=2592000
content-security-policy: frame-ancestors 'self'
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
[Response Body]:
JSON_PARSING_ERROR: Unexpected character (d) at position 0.
[Data]: 60 bytes
[Network Duration]: 0.306522011756897s
[Serialization Duration]: 0.00016999244689941406s
[Result]: failure(Alamofire.AFError.responseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 400)))
Я также заметил, что если я удаляю тип содержимого из заголовков, ошибок не возникает, но уведомление не приходит.