import APNS
func configurePush(with app: Application) throws {
let authKey = // We specify the received key
"""
-----BEGIN PRIVATE KEY-----
BIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBABBgm90Ix8h/YbUQqbUj
wQqo3ogfEqdkyggdL2u3TBc+S2paCgYIKoZIzj0DAQehRANCAASXedEOgoqwdvdD
JTItU1gLiIFE+q/ea5CJYQBMdh1bYF/f50xFTQXNnOQQvsn86mPwYTRP00C+jb+Y
DwUFid0m
-----END PRIVATE KEY-----
"""
app.apns.configuration = try .init(
authenticationMethod: .jwt(
key: .private(pem: Data(authKey.utf8)),
keyIdentifier: "6P35MVGH68", // This is the name of the received key `AuthKey_6P35MVGH68.p8`
teamIdentifier: "1T0ZYA35RG" // Team ID. Take from the developer account
),
topic: "com.sergey.testpush", // Bundle of your iOS application
environment: .sandbox // When the app is uploaded to the App Store, change it to production
)
}
// swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "my-app",
dependencies: [
// Other dependencies...
.package(url: "https://github.com/vapor/apns.git", from: "2.0.0"),
],
targets: [
.target(name: "App", dependencies: [
// Other dependencies...
.product(name: "APNS", package: "apns")
]),
// Other targets...
]
)
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
let initialViewController = ViewController()
window.rootViewController = initialViewController
window.makeKeyAndVisible()
// Request permission for notifications
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } // From data to string
let token = tokenParts.joined()
print("Device Token: \(token)") // Save the key
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)") // Error
}
}
let alert = APNSwiftAlert(title: "Hello", subtitle: "How are you?", body: "Fine, thank You")
let aps = APNSwiftPayload(alert: alert, badge: 1, sound: .normal("newSound.wav")) // You can order your own sound. Just add it to the app
let _ = app.apns.send(aps, to: "47d27e07eeee098bdd581cca4157b7d8823c14e47b787f1a51f8a0195130cfb5") // Device id