我尝试编写应用程序以通过Firebase Cloud Messaging接收通知。当我尝试通过Firebase控制台发送消息时,它最初工作,但是当我尝试使用PHP webservice做同样的事情时,作为回应,它显示成功,但我既没有收到消息也没有我能够再收到任何通知通过Firebase控制台。我该如何解决这个问题?
我在服务器端的代码:
<?php
function send_notification ($tokens, $message)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$fields = array(
'registration_ids' => $tokens,
'data' => $message
);
$headers = array(
'Authorization:key = AIzaSyDjrLKZGs4OcIgBPxpFnTzGeZHur4v9V8U',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
$conn = mysqli_connect("localhost:3306", "minaaaa", "tt@2018", "dbSurvey");
$sql = "Select Token From users";
$result = mysqli_query($conn,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
$tokens[] = $row["Token"];
}
}
mysqli_close($conn);
$message = array("message" => " FCM PUSH NOTIFICATION TEST MESSAGE");
$message_status = send_notification($tokens, $message);
echo $message_status;
?>
Swift中的代码:
UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Util.copyFile(fileName: "db.zanjanwireFinal01.db")
//let alert = UIAlertController(title: title, message: message , preferredStyle: .alert)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]){(isGranted, err)
in
if err != nil {
}
else
{
UNUserNotificationCenter.current().delegate = self
Messaging.messaging().delegate = self
if let token = InstanceID.instanceID().token() {
print("DCS: " + token)
self.RegisterUsers(testStr: token)
}
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
FirebaseApp.configure()
return true
}
func ConnectToFCM() {
Messaging.messaging().shouldEstablishDirectChannel = true
if let token = InstanceID.instanceID().token() {
print("DCS: " + token)
RegisterUsers(testStr: token)
}
}
func RegisterUsers(testStr:String){
let request = NSMutableURLRequest(url: NSURL(string:
request.httpMethod = "POST"
var dataString = "Token=\(testStr)"
print (dataString)
request.httpBody = dataString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("fffffffffatemeeeeeee")
print("error=\(error)")
return
}
print("response = \(response)")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}
task.resume()
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to
// inactive state. This can occur for certain types of
// temporary interruptions (such as an incoming phone call
// or SMS message) or when the user quits the application
// and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers,
// and invalidate graphics rendering callbacks. Games
// should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user
// data, invalidate timers, and store enough application
// state information to restore your application to its
// current state in case it is terminated later.
// If your application supports background execution, this
// method is called instead of applicationWillTerminate:
// when the user quits.
//FirstMenueViewController().update()
Messaging.messaging().shouldEstablishDirectChannel = false
}
func applicationWillEnterForeground(_ application: UIApplication) {
FirstMenueViewController().update()
// Called as part of the transition from the background
// to the active state; here you can undo many of the
// changes made on entering the background.
ConnectToFCM()
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started)
// while the application was inactive. If the application
// was previously in the background, optionally refresh
// the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate.
// Save data if appropriate. See also
// applicationDidEnterBackground:.
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
ConnectToFCM()
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
UIApplication.shared.applicationIconBadgeNumber += 1
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "com.DouglasDevlops.BadgeWasUpdated"), object: nil)
}