7.
Expanding the Application
Written by Scott Grosch
Now that you’ve got a database up and running, you need to tell your app how to connect to it. As you saw in the previous chapter, “Server Side Pushes,” Vapor will run a local server for you at an address like http://192.168.1.1:8080 (change with your own IP address).
This is the URL that your app will need to talk to if you successfully registered for push notifications. Of course, remember to substitute your IP address in the URL.
Token Details
You’ll want to be able to pass appropriate details to your web service which describes the user’s push notification registration.
Open the starter project from this chapter’s materials, then create a new Swift file called TokenDetails.swift and add the following code:
struct TokenDetails {
let token: String
let debug: Bool
}
Your web service expects JSON data, so add an encoder to the top of the struct:
private let encoder = JSONEncoder()
To use the JSONEncoder, your struct must conform to Encodable. Add the following extension:
extension TokenDetails: Encodable {
private enum CodingKeys: CodingKey {
case token, debug
}
}
You need to explicitly specify the CodingKeys because Swift, by default, will attempt to encode each property. You don’t want to encode the encoder, though. By specifying the keys of token and debug Swift knows to only encode those two properties.
Now you can implement the method which will return the encoded data. Add the following inside TokenDetails:
func encoded() -> Data {
return try! encoder.encode(self)
}
While fully functional, there’s one more piece to implement. When you’re debugging your app, you’ll want to have an easy way to see what is being sent to the web service.
Add another extension:
extension TokenDetails: CustomStringConvertible {
var description: String {
return String(data: encoded(), encoding: .utf8) ?? "Invalid token"
}
}
CustomStringConvertible lets Swift know that when you pass this struct to print that it should call your custom implementation of the description property.
The last piece left is to add an initializer to TokenDetails:
init(token: Data) {
self.token = token.reduce("") { $0 + String(format: "%02x", $1) }
#if DEBUG
encoder.outputFormatting = .prettyPrinted
debug = true
print(String(describing: self))
#else
debug = false
#endif
}
The DEBUG macro will be true when you’re running your app from Xcode. Using the .prettyPrinted setting makes the JSON output more human friendly. As you add more items to the data that you send during registration, these “pretty” lines become a life saver when debugging.
You might, for example, want to store the users’ preferred language. By storing the language on your server, you’ll be able to periodically examine the list of languages to determine whether you should consider localizing your app to another language. Add a new property to TokenDetails:
let language: String
Then set the value in the initializer, just after assigning the token:
language = Locale.preferredLanguages[0]
Finally, add language to the enum:
case token, debug, language
Sending the Tokens
Now that you have a way to generate the details which will be sent, replace the application(_:didRegisterForRemoteNotificationsWithDeviceToken:) method body in AppDelegate.swift with the following code:
guard let url = URL(string: "http://192.168.1.1:8080/api/token") else {
fatalError("Invalid URL string")
}
You first declare the URL you’ll send your token to. Remember to update the IP address with the IP of your Mac that you discovered in Chapter 6, “Server-Side Pushes”.
Next, create an instance of TokenDetails in the method:
let details = TokenDetails(token: deviceToken)
Finally, finish the method by sending the request:
Task {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = details.encoded()
_ = try await URLSession.shared.data(for: request)
}
While application(_:didRegisterForRemoteNotificationsWithDeviceToken:) is not asynchronous, the data(for:) method is. By creating a new Task block you allow the delegate method to complete while the connection to your web server is handled in the background.
Notice that you’re not checking the status of the request. If the registration with your web site or database were to fail for any reason, you wouldn’t tell your end user this as there isn’t anything they can do about it anyway. Hopefully, the next time they run your app, you would’ve fixed the server-side issue and the registration will complete successfully.
If you try to run this now, you’ll get errors as Apple blocks the URL due to App Transport Security, or ATS. In a production app, you’d probably want to connect to secure website with the TLS protocol (i.e. https websites). Since this is only a development example, you can disable that security measurement.
Select PushNotifications at the top of the project window and then select the PushNotifications target. On the tab bar select Info. Add a new entry for App Transport Security Settings and then perform these three steps:
- Expand your newly created App Transport Security Settings using the chevron on the left.
- Right-click on App Transport Security Settings and choose Add Row.
- Set the key to be Allow Arbitrary Loads and the value to be YES.
Testing
Note: For this to work, you need to make sure an instance of your Vapor server is running and configured to run on your IP address, as well as make sure your database is running. You also need to set up the sendPushes.php script to use your APNs token. This is all described in Chapter 6, “Server-Side Pushes”.
Build and run your app on a physical device. Put the app into the background by going to your home screen or locking your phone.
At this point, if you run the sendPushes.php script that you created in Chapter 6, “Server-Side Pushes,” you should get a push notification!
Refactor for Reuse
You can probably already see how the push notification code will be almost exactly the same in every project you create. Do a little cleanup by moving this common code to a new file called PushNotifications. Add the following code to the file:
import UIKit
import UserNotifications
enum PushNotifications {
static func send(token: Data, to url: String) {
guard let url = URL(string: url) else {
fatalError("Invalid URL string")
}
Task {
let details = TokenDetails(token: token)
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = details.encoded()
_ = try await URLSession.shared.data(for: request)
}
}
static func register(in application: UIApplication) {
Task {
let center = UNUserNotificationCenter.current()
try await center.requestAuthorization(options: [.badge, .sound, .alert])
await MainActor.run {
application.registerForRemoteNotifications()
}
}
}
}
By using an enum you ensure that all of your methods are static and that you won’t accidentially initialize an instance of PushNotifications.
Switch back to AppDelegate.swift and replace the class with the following simplified code:
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
PushNotifications.register(in: application)
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
PushNotifications.send(token: deviceToken, to: "http://192.168.1.1:8080")
}
}
You could, of course, leave the code in AppDelegate.swift. However, many of your apps will have other requirements for the application delegate unrelated to push notifications. By extracting that code into a file of its own you make future projects easier to configure. Simply copy the PushNotifications.swift file into the project and add a line to the appropriate delegate methods.
Key Points
- Once you have your database established, you need to tell your app how to connect to it. Vapor will allow you to run a server written with Swift.
- Take the time to add some additional lines at the end of notification registration to display the body of the JSON request in a “pretty,” easy-to-read format, which can help in the future with debugging.
Where to Go From Here?
And there you have it! You’ve successfully built an API that saves device tokens and an app that consumes that API. This is the basic skeleton you will build upon when using push notifications. In Chapter 8, “Handling Common Scenarios,” you will start handling common push notification scenarios, such as displaying a notification while the app is in the foreground… so keep reading!