2016-08-03 73 views
-1

我一直在嘗試將HTTP發佈請求發送到Firebase雲消息服務器。這是我一直在使用的代碼,我得到以下回應。根據Firebase文檔,該消息應該已發送,但不會在我將其發送到我的設備時顯示,不在背景中,也不在didReceiveRemoteNotification中。爲什麼消息不會顯示出來?Swift中的HTTP發佈

Body:Optional({"multicast_id":9176652856657890066,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1470318910131254%0753194407531944"}]}) 

Error: nil 
Success: Optional(1) 

下面的代碼:

let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")! 
     let session = NSURLSession.sharedSession() 

     let request = NSMutableURLRequest(URL: url) 
     request.HTTPMethod = "POST" 
     request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData 
     let dictionary = ["notification":["title":"BBM","text": message,"project_id": "marketplace-management","registration_id":token!]] as AnyObject 
     do { 
      try request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted) 
     } catch {} 
     request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.addValue("key=myKey", forHTTPHeaderField: "Authorization") 

     let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
      print("Response: \(response)") 
      let strData = NSString(data: data!, encoding: NSUTF8StringEncoding) 
      print("Body: \(strData)") 
      print("Error: \(error)") 
      var json = NSDictionary() 
      do { json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! NSDictionary } catch {} 
      let parseJSON = json 
      let success = parseJSON["success"] as? Int 
      print("Success: \(success)") 
     }) 
     task.resume() 
+1

「它似乎並不奏效」 - 請編輯您的問題,包括您收到的確切的錯誤消息。此外,向我們展示「響應」是什麼(狀態碼,特別是幫助診斷正在發生的事情)。 – Rob

回答

2
let dictionary = ["notification":["title":"","text": message,"project_id": "myProjectID","to":token]] 
    print(dictionary)//["notification": ["title": "", "project_id": "myProjectID", "to": "12", "text": "message"]] 
    do { 
     try request.HTTPBody = NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted) 
    } catch {}