プッシュ通知を利用するための設定等は割愛します。
// コンソールから確認できます
let serverKey: String = "xxxxxxxxx"
// プッシュ通知を送るユーザーのトークン
let token: String = "xxxxxxxxx"
let post: [String: Any] = ["to": token,
"priority": "high", // highにするとアプリが非起動時・バックグラウンドでも通知が来る
"notification": [
"badge": 1,
"body": "お笑いコンビ「インパルス」の堤下敦さんが14日午前2時半ごろ、東京・狛江市で睡眠薬を飲んだあとに車を運転していたことが警視庁への取材でわかりました。",
"title": "インパルス堤下さん謝罪「湿疹で眠れず睡眠薬」"]
]
var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
do {
request.httpBody = try JSONSerialization.data(withJSONObject: post, options: JSONSerialization.WritingOptions())
print("Succeeded serialization.: \(post)")
} catch {
print("Failed serialization.: \(error)")
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let realResponse = response as? HTTPURLResponse {
if realResponse.statusCode == 200 {
print("Succeeded post!")
} else {
print("Failed post: \(realResponse.statusCode)")
}
}
if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
print("POST: \(postString)")
}
}
task.resume()