2016-05-26 20 views
1

Google's Firebase websiteで、ダウンストリームメッセージを送信するために、HTTP POST要求を行う必要があります。これは、それが何を言っていることです:SwiftでHTTP POSTリクエストを作成する

は、サーバーから下流にメッセージを送信:

を下流のメッセージに対処または「標的」には、アプリケーションサーバは、受信したクライアントアプリの登録トークンを に設定します。事前定義されたフィールドまたはカスタムデータメッセージを使用して 通知メッセージを送信できます。 ペイロードの詳細については、メッセージペイロードの通知とデータを参照してください。このページの例では、HTTPメッセージとXMPPプロトコルでデータメッセージ を送信する方法を示しています。

HTTP POSTリクエスト

https://fcm.googleapis.com/fcm/send 
Content-Type:application/json 
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA 

{ "data": { 
    "score": "5x1", 
    "time": "15:10" 
    }, 
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." 
} 

私はスウィフト2でこれをどのように行うのですか?

答えて

3

人々はこの質問を落としました。それは残念です。私は4ヶ月以上このトピックを研究してきました。他のstackoverflowの質問/回答は私を助けませんでした。

とにかく、GoogleのFirebase Cloudダウンストリームメッセージに固有の解決策を見つけました。これは、HTTP POSTリクエストを介してすべてのユーザーに通知をプッシュするメッセージをGoogleサーバーに送信します。

以下のコードを実行する前に、Firebase用のiOSクライアントの設定、正しいポッドのすべてのインストール、証明書の取得、プロビジョニングプロファイルの取得などの手順に従ってください。here

ビューコントローラ:

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() 
} 

アプリの委任:

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") 
} 

誰か質問がある場合は、お気軽にお尋ねください!私はトピックに送る方法も知っています。

ありがとうございます!

+0

このソリューションを使用すると、サーバー鍵が公開され、アプリケーションが危険にさらされます。 – goblin

+0

あなたがしていることを知っているように思えるので、より良い方法を説明してください! –

+0

これは素晴らしいことですが、私はあなたのアプリをどのように妥協するのか分かりませんが、私は自分のアプリでそれをやっています。ありがとうございました! –

関連する問題