feat(readme): update readme with better swift

This commit is contained in:
Matthew Podwysocki 2019-03-19 15:32:32 -04:00 коммит произвёл GitHub
Родитель 9cc1d76334
Коммит 5054841e35
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
1 изменённых файлов: 60 добавлений и 63 удалений

Просмотреть файл

@ -8,7 +8,7 @@ This app handles the following scenarios
- Receive push notifications
- Receive silent push notifications
## Getting Started.
## Getting Started
The sample application requires the following:
- macOS Sierra+
@ -23,77 +23,74 @@ To run the application, update the following values in `Info.plist` with values
Once the values have been updated, build the application and deploy to your device. From there, you can register the device, set tags used to target the device, and unregister the device.
## Setting up the notification code
## Setting up the Notification Code
Diving into the sample code, we can use the SDK to connect to the service using the connection string and hub name from `Info.plist`.
```objc
- (SBNotificationHub *)getNotificationHub {
NSString *hubName = [[NSBundle mainBundle] objectForInfoDictionaryKey:NHInfoHubName];
NSString *connectionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:NHInfoConnectionString];
```swift
func getNotificationHub() -> SBNotificationHub {
let NHubName = Bundle.main.object(forInfoDictionaryKey: Constants.NHInfoHubName) as? String
let NHubConnectionString = Bundle.main.object(forInfoDictionaryKey: Constants.NHInfoConnectionString) as? String
return [[SBNotificationHub alloc] initWithConnectionString:connectionString notificationHubPath:hubName];
return SBNotificationHub.init(connectionString: NHubConnectionString, notificationHubPath: NHubName)
}
```
We can then register for push notifications (with options to enable sound and badge updates) using the following code:
```objc
@IBAction func handleRegister(_ sender: Any) {
// Save raw tags text in storage
UserDefaults.standard.set(tagsTextField.text, forKey: Constants.NHUserDefaultTags)
```swift
@IBAction func handleRegister(_ sender: Any) {
// Save raw tags text in storage
UserDefaults.standard.set(tagsTextField.text, forKey: Constants.NHUserDefaultTags)
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
granted, error in
if (error != nil) {
print("Error requesting for authorization:");
}
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
UNUserNotificationCenter.current()
.requestAuthorization(options: [.alert, .sound, .badge]) {
granted, error in
if (error != nil) {
print("Error requesting for authorization:");
}
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let unparsedTags = UserDefaults.standard.string(forKey: Constants.NHUserDefaultTags) ?? ""
let tagsArray = unparsedTags.split(separator: ",")
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let unparsedTags = UserDefaults.standard.string(forKey: Constants.NHUserDefaultTags) ?? ""
let tagsArray = unparsedTags.split(separator: ",")
let hub = getNotificationHub()
hub.registerNative(withDeviceToken: deviceToken, tags: Set(tagsArray)) {
error in
if (error != nil) {
print("Error registering for notifications: \(error.debugDescription)");
} else {
showAlert("Registered", withTitle:"Registration Status");
}
}
}
let hub = getNotificationHub()
hub.registerNative(withDeviceToken: deviceToken, tags: Set(tagsArray)) {
error in
if (error != nil) {
print("Error registering for notifications: \(error.debugDescription)");
} else {
showAlert("Registered", withTitle:"Registration Status");
}
}
}
```
We can also unregister the device from the Azure Notification Hub with the following code:
We can also unregister the device from the Azure Notification Hub with the following code:
```objc
```swift
@IBAction func handleUnregister(_ sender: Any) {
let hub = getNotificationHub()
hub.unregisterNative { error in
if (error != nil) {
print("Error unregistering for push: \(error.debugDescription)");
} else {
showAlert("Unregistered", withTitle: "Registration Status")
}
}
}
let hub = getNotificationHub()
hub.unregisterNative { error in
if (error != nil) {
print("Error unregistering for push: \(error.debugDescription)");
} else {
showAlert("Unregistered", withTitle: "Registration Status")
}
}
}
```
## Handle a push notification
## Handle a Push Notification
In order to demonstrate handling a push notification, use the Azure Portal for your Notification Hub and select "Test Send" to send messages to your application. For example, we can send a simple message to our device by selecting the Apple Platform, adding your selected tags and the following message body:
```
```json
{
"aps": {
"alert": {
@ -108,29 +105,29 @@ Diving into the code, the push notifications are handled by the following two `U
The `userNotificationCenter:willPresent:withCompletionHandler:` method handles notifications when the app is in the foreground (before the notification is optionally displayed to the user):
```objc
```swift
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Your code here
}
```
The `userNotificationCenter:didReceive:withCompletionHandler:` method handles notifications when the app is in the background, _and_ the user taps on the system notification:
```objc
```swift
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// Your code here
}
```
## Handle a silent push
## Handle a Silent Push
The iOS platform allows for [silent notifications](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_updates_to_your_app_silently?language=objc) which allow you to notify your application when new data is available, without displaying that notification to the user. Using the "Test Send" capability, we can send a silent notification using the `content-available` property in the message body.
```
```json
{
"aps": {
"content-available": 1
@ -140,10 +137,10 @@ The iOS platform allows for [silent notifications](https://developer.apple.com/d
To handle this scenario in code, implement the `UIApplicationDelegate` method `application:didReceiveRemoteNotification:fetchCompletionHandler:`:
```objc
```swift
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Your code here
}
```