在Swift 2中发出HTTP POST请求

时间:2016-05-26 14:25:31

标签: swift firebase push-notification firebase-cloud-messaging httprequest

Google's Firebase website上,为了发送下游消息,我必须执行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..."
}

如何在Swift 2中执行此操作?

2 个答案:

答案 0 :(得分:4)

人们对这个问题进行了投票,这是一种耻辱。我已经研究了这个主题超过4个月了,没有其他的stackoverflow问题/答案帮助了我。

无论如何,我找到了针对Google Firebase Cloud下游消息传递的解决方案。这会向Google服务器发送一条消息,通过HTTP POST请求将通知推送给所有用户。

在执行以下任何代码之前,请务必按照以下步骤为Firebase设置iOS客户端,安装所有正确的pod并获取证书,配置配置文件等。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()
}

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

如果有人有任何疑问,请随时提出!我也知道如何发送主题。

谢谢!

答案 1 :(得分:1)

解决方案更新

Swift 4 +进一步了解如何在Swift中调整FCM

项目设置> Cloud Messaging>服务器密钥中找到服务器密钥

enter image description here

func swiftHttpPostRequest(){ 


let serverKey = <Server Key> // AAAA8c3j2...
let partnerToken = <Receiver Token> // eXDw9S52XWoAPA91....  
let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic 
let url = NSURL(string: "https://fcm.googleapis.com/fcm/send") 

let postParams = [
                   "to": partnerToken,
                   "notification": [
                   "body": "This is the body.",
                   "title": "This is the title.",
                   "sound" : true, // or specify audio name to play
                   "click_action" : "", // action when user click notification (categoryIdentifier)
                  ]] as [String : Any]

   let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

  do {
        request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
        print("My paramaters: \(postParams)")
    } catch {
        print("Caught an error: \(error)")
    } 


let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
    if let realResponse = response as? HTTPURLResponse {
        if realResponse.statusCode != 200 {
            print("Not a 200 response")
        }
    }

    if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
        print("POST: \(postString)")
    }
}

     task.resume()
}