LoginSignup
5
7

More than 5 years have passed since last update.

【Swift】Firebase Cloud MessagingでクライアントからHTTP POSTで特定のユーザーにプッシュ通知を送るコード

Last updated at Posted at 2017-06-15

プッシュ通知を利用するための設定等は割愛します。

// コンソールから確認できます
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()


5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7