Люди проголосовали за этот вопрос, и это позор. Я изучаю эту тему уже более 4 месяцев, и никакой другой вопрос/ответ stackoverflow не помог мне.
Во всяком случае, я нашел решение, специфичное для обмена сообщениями Firebase Cloud от Google. Это отправляет сообщение на сервер Google, который посылает уведомления всем пользователям через HTTP POST-запрос.
Прежде чем делать какой-либо из приведенных ниже кодов, не забудьте выполнить шаги по настройке iOS-клиента для Firebase, установки всех правильных контейнеров и получения ваших сертификатов, профиля подготовки и т. Д. here.
View Controller:
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")
let postParams: [String : AnyObject] = ["to": "<Your registration token>", "notification": ["body": "This is the body.", "title": "This is the title."]]
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("key=<Your Firebase Server Key>", forHTTPHeaderField: "Authorization")
do
{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(postParams, options: NSJSONWritingOptions())
print("My paramaters: \(postParams)")
}
catch
{
print("Caught an error: \(error)")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
if let realResponse = response as? NSHTTPURLResponse
{
if realResponse.statusCode != 200
{
print("Not a 200 response")
}
}
if let postString = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String
{
print("POST: \(postString)")
}
}
task.resume()
}
App Делегат:
var window: UIWindow?
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: nil))
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
let notificationTypes: UIUserNotificationType = [.Alert, .Badge, .Sound]
let pushNotifSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
application.registerUserNotificationSettings(pushNotifSettings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("Device Token = \(deviceToken)")
FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Sandbox)
print("Registration token: \(FIRInstanceID.instanceID().token()!)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
// For push notifications sent from within the Firebase console
if userInfo["google.c.a.c_l"] != nil
{
if let title = userInfo["google.c.a.c_l"] as? String
{
if let body = userInfo["aps"]!["alert"] as? String
{
self.displayAlert(title, message: body)
}
}
}
// For push notifications sent from within the app via HTTP POST Request
else
{
if let title = userInfo["aps"]!["alert"]!!["title"] as? String
{
if let body = userInfo["aps"]!["alert"]!!["body"] as? String
{
self.displayAlert(title, message: body)
}
}
}
}
func applicationDidEnterBackground(application: UIApplication) {
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM")
}
Если кто имеет какие-либо вопросы, пожалуйста, не стесняйтесь спрашивать! Я также знаю, как отправлять темы.
Спасибо!
Используя это решение, вы обнаружите свой серверный ключ, который нарушит ваше приложение. – goblin
Пожалуйста, объясните лучший способ сделать это, поскольку вам кажется, что вы знаете, что делаете! –
Это здорово, я не знаю, как это могло бы скомпрометировать ваше приложение, но я получил его работу над своим приложением. Спасибо! –