إضافة إشعارات فورية إلى تطبيق iOS الخاص بك
نظرة عامة
في هذا البرنامج التعليمي، يمكنك إضافة إعلامات الدفع إلى مشروع التشغيل السريع لنظام التشغيل iOS بحيث يتم إرسال إشعار دفع إلى الجهاز في كل مرة يتم فيها إدراج سجل.
إذا كنت لا تستخدم مشروع خادم التشغيل السريع الذي تم تنزيله ، فستحتاج إلى حزمة ملحق إعلام الدفع. لمزيد من المعلومات، راجع دليل العمل باستخدام حزمة SDK لخادم الواجهة الخلفية .NET لتطبيقات Azure للأجهزة المحمولة.
لا يدعم محاكي iOS إشعارات الدفع. تحتاج إلى جهاز iOS فعلي وعضوية في برنامج مطوري Apple.
تكوين مركز الإشعارات
تستخدم ميزة تطبيقات الأجهزة المحمولة في Azure App Service مراكز إعلام Azure لإرسال الدفعات، لذلك ستقوم بتكوين مركز إعلام لتطبيق الجوال الخاص بك.
في مدخل Azure، انتقل إلى خدمات التطبيقات، ثم حدد الواجهة الخلفية لتطبيقك. ضمن الإعدادات، حدد دفع.
لإضافة مورد مركز إشعارات إلى التطبيق، حدد الاتصال. يمكنك إما إنشاء موزع أو الاتصال بمركز موجود.

لقد قمت الآن بتوصيل مركز إعلام بمشروعك الخلفي لتطبيقات الجوال. في وقت لاحق يمكنك تكوين مركز الإعلام هذا للاتصال بنظام إعلام النظام الأساسي (PNS) للدفع إلى الأجهزة.
تسجيل التطبيق للحصول على إشعارات الدفع
- سجل معرف تطبيق لتطبيقك. قم بإنشاء معرف تطبيق صريح (وليس معرف تطبيق أحرف البدل) ، وبالنسبة إلى معرف الحزمة، استخدم معرف الحزمة الدقيق الموجود في مشروع التشغيل السريع Xcode. من المهم أيضا تحديد خيار دفع الإشعارات .
- بعد ذلك ، للتحضير لتكوين إشعارات الدفع ، قم بإنشاء شهادة SSL "تطوير" أو "توزيع".
تكوين Azure لإرسال إعلامات فورية
- على ال Mac، قم بتشغيل الوصول إلى سلسلة المفاتيح. على شريط التنقل الأيمن، ضمن الفئة، افتح شهاداتي. ابحث عن شهادة SSL التي قمت بتنزيلها في القسم السابق، ثم قم بالكشف عن محتوياتها. حدد الشهادة فقط (لا تحدد المفتاح الخاص). ثم قم بتصديره.
- في مدخل Azure، حدد استعراضخدمات AllApp>. ثم حدد الواجهة الخلفية لتطبيقات الجوال.
- ضمن الإعدادات، حدد دفع خدمة التطبيق. ثم حدد اسم مركز الإشعارات.
- انتقل إلى خدمات >إشعارات الدفع من AppleUpload شهادة. Upload الملف .p12، وتحديد الوضع الصحيح (اعتمادا على ما إذا كانت شهادة SSL الخاصة بالعميل من وقت سابق هي الإنتاج أو وضع الحماية). احفظ أي تغييرات.
تم تكوين خدمتك الآن للعمل مع الإعلامات المباشرة على iOS.
تحديث الواجهة الخلفية لإرسال إشعارات فورية
الواجهة الخلفية .NET (C #):
في Visual Studio، انقر بزر الماوس الأيمن فوق مشروع الخادم وانقر على إدارة حزم NuGet، وابحث عن
Microsoft.Azure.NotificationHubs، ثم انقر فوق تثبيت. يؤدي ذلك إلى تثبيت مكتبة مراكز الإشعارات لإرسال الإشعارات من الواجهة الخلفية.في مشروع Visual Studio الواجهة الخلفية، افتح ControllersTodoItemController>.cs. في أعلى الملف، أضف العبارة التالية
using:using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.NotificationHubs;استبدل الأسلوب
PostTodoItemبالتعليمات البرمجية التالية:public async Task<IHttpActionResult> PostTodoItem(TodoItem item) { TodoItem current = await InsertAsync(item); // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // iOS payload var appleNotificationPayload = "{\"aps\":{\"alert\":\"" + item.Text + "\"}}"; try { // Send the push notification and log the results. var result = await hub.SendAppleNativeNotificationAsync(appleNotificationPayload); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } return CreatedAtRoute("Tables", new { id = current.Id }, current); }إعادة نشر مشروع الخادم.
Node.js الخلفية:
قم بإعداد مشروع الواجهة الخلفية.
استبدال البرنامج النصي الجدول todoitem.js بالتعليمة البرمجية التالية:
var azureMobileApps = require('azure-mobile-apps'), promises = require('azure-mobile-apps/src/utilities/promises'), logger = require('azure-mobile-apps/src/logger'); var table = azureMobileApps.table(); // When adding record, send a push notification via APNS table.insert(function (context) { // For details of the Notification Hubs JavaScript SDK, // see https://aka.ms/nodejshubs logger.info('Running TodoItem.insert'); // Create a payload that contains the new item Text. var payload = "{\"aps\":{\"alert\":\"" + context.item.text + "\"}}"; // Execute the insert; Push as a post-execute action when results are returned as a Promise. return context.execute() .then(function (results) { // Only do the push if configured if (context.push) { context.push.apns.send(null, payload, function (error) { if (error) { logger.error('Error while sending push notification: ', error); } else { logger.info('Push notification sent successfully!'); } }); } return results; }) .catch(function (error) { logger.error('Error while running context.execute: ', error); }); }); module.exports = table;عند تحرير الملف على الكمبيوتر المحلي، أعد نشر مشروع الخادم.
إضافة إشعارات فورية إلى التطبيق
الهدف جيم:
في QSAppDelegate.m، قم باستيراد iOS SDK وQSTodoService.h:
#import <MicrosoftAzureMobile/MicrosoftAzureMobile.h> #import "QSTodoService.h"في
didFinishLaunchingWithOptionsQSAppDelegate.m، أدخل الأسطر التالية قبل ذلكreturn YES;مباشرة:UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; [[UIApplication sharedApplication] registerForRemoteNotifications];في QSAppDelegate.m، أضف طرق المعالج التالية. يتم الآن تحديث تطبيقك لدعم الإشعارات الفورية.
// Registration with APNs is successful - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { QSTodoService *todoService = [QSTodoService defaultService]; MSClient *client = todoService.client; [client.push registerDeviceToken:deviceToken completion:^(NSError *error) { if (error != nil) { NSLog(@"Error registering for notifications: %@", error); } }]; } // Handle any failure to register - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError: (NSError *)error { NSLog(@"Failed to register for remote notifications: %@", error); } // Use userInfo in the payload to display an alert. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSLog(@"%@", userInfo); NSDictionary *apsPayload = userInfo[@"aps"]; NSString *alertString = apsPayload[@"alert"]; // Create alert with notification content. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Notification" message:alertString preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Cancel"); }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { NSLog(@"OK"); }]; [alertController addAction:cancelAction]; [alertController addAction:okAction]; // Get current view controller. UIViewController *currentViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; while (currentViewController.presentedViewController) { currentViewController = currentViewController.presentedViewController; } // Display alert. [currentViewController presentViewController:alertController animated:YES completion:nil]; }
سويفت:
إضافة ملف ClientManager .swift مع المحتويات التالية. استبدل ٪ AppUrl٪ بعنوان URL للواجهة الخلفية لتطبيق Azure للأجهزة المحمولة.
class ClientManager { static let sharedClient = MSClient(applicationURLString: "%AppUrl%") }في ToDoTableViewController.swift، استبدل السطر الذي يقوم بتهيئة
MSClientالسطرlet clientبهذا السطر:let client = ClientManager.sharedClientفي AppDelegate.swift، يستعاض عن
func applicationالنص الأساسي كما يلي:func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings( UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) application.registerForRemoteNotifications() return true }في AppDelegate.swift، أضف طرق المعالج التالية. يتم الآن تحديث تطبيقك لدعم الإشعارات الفورية.
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { ClientManager.sharedClient.push?.registerDeviceToken(deviceToken) { error in print("Error registering for notifications: ", error?.description) } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Failed to register for remote notifications: ", error.description) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) { print(userInfo) let apsNotification = userInfo["aps"] as? NSDictionary let apsString = apsNotification?["alert"] as? String let alert = UIAlertController(title: "Alert", message: apsString, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default) { _ in print("OK") } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { _ in print("Cancel") } alert.addAction(okAction) alert.addAction(cancelAction) var currentViewController = self.window?.rootViewController while currentViewController?.presentedViewController != nil { currentViewController = currentViewController?.presentedViewController } currentViewController?.presentViewController(alert, animated: true) {} }
اختبار الإشعارات المباشرة
- في Xcode ، اضغط على تشغيل وبدء تشغيل التطبيق على جهاز iOS (لاحظ أن الدفع لن يعمل على أجهزة المحاكاة). انقر فوق موافق لقبول الإشعارات الفورية; يحدث هذا الطلب في المرة الأولى التي يتم فيها تشغيل التطبيق.
- في التطبيق، أضف عنصرا جديدا وانقر على +.
- تحقق من استلام إشعار، ثم انقر على موافق لرفض الإشعار. لقد أكملت الآن هذا البرنامج التعليمي بنجاح.
المزيد
- تمنحك القوالب المرونة لإرسال دفعات عبر الأنظمة الأساسية ودفعات مترجمة. كيفية استخدام مكتبة عملاء iOS لتطبيقات Azure للأجهزة المحمولة توضح لك كيفية تسجيل القوالب.