Start using Swift to develop iOS 10-26 using local user notifications

Start using Swift to develop iOS 10-26 using local user notifications

IOS 10 before the user notification is relatively simple, iOS 10 allows users to inform more abundant, you can have static pictures, dynamic GIF, video, audio and so on.

Start using Swift to develop iOS 10-26 using local user notifications

The user notification can appear in the notification center, the main screen, the lock screen, when the user missed the user notification, you can look at the notification center.

Start using Swift to develop iOS 10-26 using local user notifications

User notifications fall into two categories:

  • Local notification. Triggered by the application itself and the user device itself. For example, based on the user’s location app, the user enters a particular area to send a notification; the to-do list app sends notifications at certain times.
  • Remote notification. The remote server first sends the Notification server (Apple, Push, Service, APNS), and then passes the APNS push notifications to the user device.

This article only discusses local notifications.

Local notifications with three different triggers:

  • Specific amount of time. For example, 10 minutes later.
  • Specific date and time points.
  • Specific location.

Asking for user authorization

Sending a notification to the user is allowed by the user.

  • Add import UserNotifications in AppDelegate.swift
  • In application (_: didFinishLaunchingWithOptions:) (UNUserNotificationCenter.current) method to add authorization.RequestAuthorization (options: [.alert,.Sound,.Badge], completionHandler: {(granted, error) in if granted {print (“User notifications are allowed.”)} else {print (“User notifications are not allowed.”)}})
Start using Swift to develop iOS 10-26 using local user notifications

Create notification

General structure of notification:

Start using Swift to develop iOS 10-26 using local user notifications

The notification is represented by the UNMutableNotificationContent class.

  • Add a method in RestaurantTableViewController
Func prepareNotification (sure the) {/ / Make restaurant array is not empty if restaurants.count < 0 = {return} / / 1 let randomNum = Int (arc4random_uniform (UInt32 (restaurants.count))) let suggestedRestaurant = restaurants[randomNum] content = UNMutableNotificationContent (let / 2) content.title = "Restaurant Recommendation" = "content.subtitle Try new food today" content.body = "I recommend you to check / out (suggestedRestaurant.name.The restaurant is one!) of your favorites. It is located / at (suggestedRestaurant.location Would you like!). To give it a try?" content.sound = UNNotificationSound.default (Le / 3) T trigger UNTimeIntervalNotificationTrigger (timeInterval: = 10, repeats: = false) let request UNNotificationRequest (identifier: foodpin.restaurantSuggestion, content: content, trigger: trigger Schedule the notification (UNUserNotificationCenter.current) /.Add (request) withCompletionHandler:, Nil)}
  • 1 get a random Restaurant
  • 2 get a notification through UNMutableNotificationContent, configure parameters, and sound indicate the need to notify the sound.
  • 3 UNTimeIntervalNotificationTrigger is a time trigger, and for good testing, notify 10s once.
  • Implement upper functions in viewDidLoad. PrepareNotification ()

Now run, note that the application does not accept the notification of this application, so immediately enter the main screen or lock screen after the operation. The notification itself is highly restricted, the content is too long to display, and it can be displayed as long as it slides down.

Start using Swift to develop iOS 10-26 using local user notifications

Add pictures to the notification

Rich text content such as pictures is added through the attachments attribute of UNMutableNotificationContent, and the attachments property is an array of UNNotificationAttachment. UNNotificationAttachment can be pictures, audio, sound effects, video files.

  • Before the trigger in prepareNotification: 1 let / / add code tempDirURL = URL (fileURLWithPath:), isDirectory: NSTemporaryDirectory (true) let tempFileURL = tempDirURL.appendingPathComponent (“suggested-restaurant.jpg”) if let image (data: = UIImage suggestedRestaurant.image! As Data) {/ / 2 try? UIImageJPEGRepresentation (image, 1)?.write (to: tempFileURL) if let restaurantImage = try? UNNotificationAttachment (identifier: restaurantImage, url: tempFileURL, options: Nil) {content.attachments}} = [restaurantImage] 1 due to the use of Core Data, the picture is stored in a NSData form, so the use of NSTemporaryDirectory to generate a temporary directory Storing a temporary picture file 2 UIImageJPEGRepresentation is used to generate JPG image files

Run view, also slide down to view integrity.

Start using Swift to develop iOS 10-26 using local user notifications

Interaction with notifications

This is the default interaction before clicking on the notification into the application’s interaction.

  • Before the trigger in prepareNotification add code: / / = “foodpin.restaurantaction” categoryIdentifer 1 Let 3 let = UNNotificationAction (makeReservationAction / identifier: “foodpin.makeReservation” title: “Reserve a table”, options: [.foreground] let UNNotificationAction (identifier:) cancelAction = “foodpin.cancel” title: “Later” options:, []) / / 4 let category = UNNotificationCategory (identifier:, categoryIdentifer, actions:[makeReservationAction, cancelAction], intentIdentifiers: [], options: []) 5 (.SetNotificationCategories) / UNUserNotificationCenter.current ([category]) content.categoryIdentifier = categoryIdentifer 1,2 categoryIdentifier / / 2 is made Associate notice and Category 3 UNNotificationAction is similar to UIAlertAction options: [.foreground], said that application to the front, is to start the application of 4 UNNotificationCategory is similar to UIAlertController 5 UNNotificationCategory registered to the user center
Start using Swift to develop iOS 10-26 using local user notifications

Processing Actions

The above options: [.foreground] just started the application and did not perform specific operations. UNUserNotificationCenterDelegate userNotificationCenter (_: didReceive:withCompletionHandler:) calling method is selected in the UNNotificationAction, in this method can realize the specific operation.

  • Let AppDelegate conform to protocol UNUserNotificationCenterDelegate
  • UserNotificationCenter (_: didReceive:withCompletionHandler:) func userNotificationCenter (center: UNUserNotificationCenter didReceive _, response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping (-&gt); Void) {/ / 1 if response.actionIdentifier = = “foodpin.makeReservation” {print (“Make reservation…”) 2 if let response.notification.request.content.userInfo[/ / phone = “phone”] {let (phone = “tel:/// telURL” if let URL) = URL (string: telURL) {if UIApplication.shared.canOpenURL (URL) {print (“calling / (telURL)”) / 3 UIApplication.shared.open (URL) } completionHandler ()} 1 corresponds to the identifier that was created when UNNotificationAction was created. The UNMutableNotificationContent in the prepareNotification function is created before the 2 response.notification.request.content corresponds, and the userInfo property can be used to store the data that the notification wants to pass. For example, in the prepareNotification function, add content.userInfo = [phone:: suggestedRestaurant.phone], here you can get. 3 make a call.
  • Add UNUserNotificationCenter.current () =.Delegate = self in content.userInfo = [[phone]: suggestedRestaurant.phone]].

Code

Beginning-iOS-Programming-with-Swift

Explain

This article is a book from appcode Beginning iOS 10 Programming with Swift

Catalog

  • Begin using Swift to develop iOS 10-1 prefaces and directories
  • Start developing iOS 10-2, Hello, World with Swift! The first Swift APP
  • Start developing iOS 10-3 with Swift, introducing Auto Layout
  • Start developing iOS 10-4 with Swift and design UI with Stack View
  • Start using Swift to develop an introduction to the iOS 10-5 prototype
  • Start developing iOS 10-6 with Swift to create a simple Table Based App
  • Start using Swift to develop iOS 10-7, custom Table Views
  • Begin using Swift to develop interaction between iOS 10-8, Table, View, and UIAlertController
  • Begin using Swift to develop iOS 10-10, Navigation, Controller presentations and Segue
  • Start using Swift to develop iOS 10-11 object oriented programming
  • Start using Swift to develop iOS 10-12, rich Detail View and custom Navigation Bar
  • Start using Swift to develop iOS 10-13, Self, Sizing, Cells, and, Dynamic, Type
  • Start using Swift to develop iOS 10-14 basic animation, blur effects, and Unwind Segue
  • Start using Swift to develop iOS 10-15 using maps
  • Began developing iOS 10-16 with Swift, introducing static Table, Views, UIImagePickerController, and NSLayoutConstraint
  • Start using Swift to develop iOS 10-17 using Core Data
  • Start using Swift to develop iOS 10-18, Search, Bar, and UISearchController
  • Start using Swift to develop iOS 10-19 and build the presentation page using UIPageViewController
  • Start developing iOS 10-20 with Swift, using Tab, Bar, Controller, and splitting Storyboard
  • Start using Swift to develop iOS 10-21, using WKWebView and SFSafariViewController
  • Start using Swift to develop iOS 10-22 using CloudKit
  • Start using Swift to develop iOS 10-24 and use TestFlight for Beta testing
  • Start using Swift to develop iOS 10-25 using 3D Touch
  • Start using Swift to develop iOS 10-26 using local user notifications