Add Communication Notification capability in my Notification Service Extension's Info.plist swift - swift

How can I added the Communication Notification capability, and in my Notification Service Extension's Info.plist in swift ?
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: #escaping (UNNotificationContent) -> Void) {
let avatar = INImage(named: "Cover")
let senderPerson = INPerson(personHandle: INPersonHandle(value: "1233211234", type: .unknown), nameComponents: personNameComponents, displayName: "Sender Name", image: avatar, contactIdentifier: nil, customIdentifier: nil, isMe: false, suggestionType: .none)
let mePerson = INPerson( personHandle: INPersonHandle(value: "1233211232", type: .unknown), nameComponents: nil, displayName: nil, image: nil, contactIdentifier: nil, customIdentifier: nil, isMe: true, suggestionType: .none)
let incomingMessagingIntent = INSendMessageIntent(recipients: [mePerson], outgoingMessageType: .outgoingMessageText, content: "Test DUde", speakableGroupName: nil, conversationIdentifier: "uid", serviceName: "caset", sender: senderPerson, attachments: [])
incomingMessagingIntent.setImage(avatar, forParameterNamed: \.sender)
let interaction = INInteraction(intent: incomingMessagingIntent, response: nil)
interaction.direction = .incoming
do {
let newContent = try request.content.updating(from: incomingMessagingIntent)
contentHandler(newContent)
} catch {
print(error)
}
}
}

Add the class name of each intent that your app supports to the NSUserActivityTypes array in your Info.plist. To support INSendMessageIntent donations.

Related

How to display actions for a local notification when it arrives on the lock screen in the notification center

My app sends local notifications. When they come in the active state of the device, then with a swipe down I can access the notification actions.
But when the notification arrives on the locked screen, there is no access to actions.
And if I click on the notification, then only "open app" is available to me.
How can I be able to use these buttons by clicking on a notification in the notification center
It's my code:
class Notifications: NSObject, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
func requestAuthorization() {
notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
func getNotificationSettings() {
notificationCenter.getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
}
}
func scheduleAlarm(date: Date, repeats: Bool) {
let content = UNMutableNotificationContent()
let userAction = "Alarm"
content.title = "Будильник"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "alarm.mp3"))
content.categoryIdentifier = userAction
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: repeats)
let identifier = "Alarm"
let request = UNNotificationRequest(identifier: identifier,
content: content,
trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Отложить на 5 мин", options: [])
let stopAction = UNNotificationAction(identifier: "Stop", title: "Отключить", options: [.destructive])
let category = UNNotificationCategory(
identifier: userAction,
actions: [snoozeAction, stopAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound])
}
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
switch response.actionIdentifier {
case UNNotificationDismissActionIdentifier:
print("Dismiss Action")
case UNNotificationDefaultActionIdentifier:
print("default")
case "Snooze":
scheduleAlarm(date: StorageManager.shared.getDatesForDatePickers().wakeUpDate + TimeInterval(60), repeats: false)
default:
break
}
completionHandler()
}
}
This is how we can achieve this on tap action
Here controller that have start button to fire notification after 5 sec.
When long press on it there is two snooze after 5 sec or comment show as a title of notification in next 5 sec.
import UIKit
import UserNotifications
class ViewController: UIViewController,UNUserNotificationCenterDelegate {
//MARK: Properties and outlets
let time:TimeInterval = 10.0
let snooze:TimeInterval = 5.0
var isGrantedAccess = false
#IBOutlet weak var commentsLabel: UILabel!
//MARK: - Functions
func setCategories(){
// Add actions
let snoozeAction = UNNotificationAction(identifier: "snooze", title: "Snooze 5 Sec", options: [])
let commentAction = UNTextInputNotificationAction(identifier: "comment", title: "Add Comment", options: [], textInputButtonTitle: "Add", textInputPlaceholder: "Add Comment Here")
// Add actions to category
let alarmCategory = UNNotificationCategory(identifier: "alarm.category",actions: [snoozeAction,commentAction],intentIdentifiers: [], options: [])
// ADd category to notification
UNUserNotificationCenter.current().setNotificationCategories([alarmCategory])
}
func addNotification(content:UNNotificationContent,trigger:UNNotificationTrigger?, indentifier:String){
let request = UNNotificationRequest(identifier: indentifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: {
(errorObject) in
if let error = errorObject{
print("Error \(error.localizedDescription) in notification \(indentifier)")
}
})
}
//MARK: - Actions
#IBAction func startButton(_ sender: UIButton) {
if isGrantedAccess{
let content = UNMutableNotificationContent()
content.title = "Alarm"
content.subtitle = "First Alarm"
content.body = "First Alarm"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "alarm.category"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: false)
addNotification(content: content, trigger: trigger , indentifier: "Alarm")
}
}
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge],
completionHandler: { (granted,error) in
self.isGrantedAccess = granted
if granted{
self.setCategories()
} else {
let alert = UIAlertController(title: "Notification Access", message: "In order to use this application, turn on notification permissions.", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
alert.addAction(alertAction)
self.present(alert , animated: true, completion: nil)
}
})
}
// MARK: - Delegates
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
let identifier = response.actionIdentifier
let request = response.notification.request
// handle tap of snooze
if identifier == "snooze"{
let newContent = request.content.mutableCopy() as! UNMutableNotificationContent
newContent.body = "Snooze 5 Seconds"
newContent.subtitle = "Snooze 5 Seconds"
let newTrigger = UNTimeIntervalNotificationTrigger(timeInterval: snooze, repeats: false)
addNotification(content: newContent, trigger: newTrigger, indentifier: request.identifier)
}
// handle tap of comment
if identifier == "comment"{
let textResponse = response as! UNTextInputNotificationResponse
commentsLabel.text = textResponse.userText
let newContent = request.content.mutableCopy() as! UNMutableNotificationContent
newContent.body = textResponse.userText
addNotification(content: newContent, trigger: request.trigger, indentifier: request.identifier)
}
completionHandler()
}
}

AVPlayer message was received but not handled

I am trying to implement a singleton class with AVPlayer in it. The key value observing throws exception. I think the object of this class is getting dealloced.
import Foundation
import UIKit
import AVKit
class Player: NSObject, ObservableObject {
var player : AVPlayer!
var playerController = AVPlayerViewController()
var presentingVC : UIViewController!
static let shared = Player()
private override init() { }
func play(urlString: String) {
let auth = Authentication()
let headers: [String: String] = ["x-auth-token" : auth.token]
let url = URL(string: urlString)
let asset = AVURLAsset(url: url!, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
let playerItem = AVPlayerItem(asset: asset)
//let avPlayer = AVPlayer(url: url!)
player = AVPlayer(playerItem: playerItem)
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.status), options: [.new, .initial], context: nil)
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.currentItem.status), options: [.new, .initial], context: nil)
let center = NotificationCenter()
center.addObserver(self, selector: Selector(("newErrorLogEntry")), name: .AVPlayerItemNewErrorLogEntry, object: player.currentItem)
center.addObserver(self, selector: Selector(("failedToPlayTillEnd")), name: .AVPlayerItemFailedToPlayToEndTime, object: player.currentItem)
playerController.player = player
presentingVC.present(playerController, animated: true) {
self.player.play()
}
}
func newErrorLogEntry(_ notification: Notification) {
guard let object = notification.object, let playerItem = object as? AVPlayerItem else {
return
}
guard let errorLog: AVPlayerItemErrorLog = playerItem.errorLog() else {
return
}
print("2")
NSLog("Error: \(errorLog)")
}
func failedToPlayToEndTime(_ notification: Notification) {
let error = notification.userInfo!["AVPlayerItemFailedToPlayToEndTimeErrorKey"]
print("3")
NSLog("Error: \(String(describing: error))")
DispatchQueue.main.async {
let alert = UIAlertController(title: "Playback error {}{}", message: "Unable to Play Channel {}{} \n", preferredStyle: UIAlertController.Style.alert)
self.playerController.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: { (UIAlertAction) in
self.playerController.dismiss(animated: true, completion: nil)
print("Cancel")
}))
}
}
}
Calling from ViewController class
Player.shared.presentingVC = self
Player.shared.play(urlString: url)
Following is the exception:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<VideoPlayer_v2.Player: 0x600001f84cc0>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: status
Observed object: <AVPlayer: 0x600001dc1550>
Change: {
kind = 1;
new = 0;
}
Looks like AVPlayer.status message is received. But the object is already de-allocated. Correct me if I am wrong.
What is the best way to separate out AVPlayer functions in a separate class other than UIViewController class?
The reason for the exception is that you are adding observers inside your Player class, but you are not observing the values. To do that, add this method in side Player class then you handle the observed values as you need:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as AnyObject? === player {
if keyPath == "status" {
// Do something like this or whatever you need to do:
if player.status == .readyToPlay {
player.play()
}
} else if keyPath == "currentItem.status" {
// Do something
} else {
// Do something
}
}
}

How to set Local Notification in without appdelegate using singleton?

Hear I have more doubt about this local notification
How to set local notification without appdelegate?
How to call the delegate with seperated controller?
Here my code!!
import Foundation
import UserNotifications
class NotificationController {
private static var privateShared: NotificationController?
static var shared: NotificationController {
if privateShared == nil {
privateShared = NotificationController()
}
return privateShared!
}
class func destroy() {
privateShared = nil
}
private let notificationCenter = UNUserNotificationCenter.current()
func registerLocalNotification(controller: UIViewController){
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
}
}
Extension of Notification class :
extension NotificationController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
func scheduleNotification(notificationType: String) {
let content = UNMutableNotificationContent() // Содержимое уведомления
let categoryIdentifire = "Delete Notification Type"
content.title = notificationType
content.body = "This is example how to create " + notificationType
content.sound = UNNotificationSound.default
content.badge = 1
content.categoryIdentifier = categoryIdentifire
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
I Can't able to configure local notification without appdelegate
any thing missing my side?
Any reference appreciate!!
Thanks.
Just starter to deal with notifications on iOS and got stuck with the same problem. Here is my implementation for using UserNotifications with singleton instance.
import Foundation
import UserNotifications
class NotificationControl {
static let shared = NotificationControl()
private let notificationCenter = UNUserNotificationCenter.current()
func requestAuthorization() {
notificationCenter.requestAuthorization(options: [.alert, .badge, .sound, .criticalAlert, .provisional]) { (granted, error) in
guard granted else { return }
print(granted)
self.getNotificationSettings()
}
}
func getNotificationSettings() {
notificationCenter.getNotificationSettings { (settings) in
print(settings)
}
}
func scheduleNotification(notificationType:String) {
let content = UNMutableNotificationContent()
content.title = notificationType
content.body = "Notification example"
content.sound = UNNotificationSound.defaultCritical
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
guard let error = error else { return }
print(error.localizedDescription)
}
}
}
AppDelegate:
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NotificationControl.shared.requestAuthorization()
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}

Swift 4 receive push notification with timer

I have userNotificationCenter willPresent func(). What i want to do is... get notification once, then get one notification every 5min if they're exists. How i can perform that?
userNotificationCenter:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
//checkUser - current account ID
//userID - from user
var timer = Timer()
let userID : String = (EVTUser.user?.id)!
if let checkUser = notification.request.content.userInfo["user_id"]{
if userID != checkUser as! String{
guard let _ = UIViewController.visibleChatViewController() else {
completionHandler([.badge, .alert, .sound])
return
}
EVTChatLogController.receiveMessage(notification: notification.request.content)
//Push display
if isTransitionChat {
isTransitionChat = false
completionHandler([.badge, .alert, .sound])
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
else{
return
}
}
else{
guard let _ = UIViewController.visibleChatViewController() else {
completionHandler([.badge, .alert, .sound])
return
}
EVTChatLogController.receiveMessage(notification: notification.request.content)
if isTransitionChat {
isTransitionChat = false
completionHandler([.badge, .alert, .sound])
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
UPDATED:
I tried to use this code but still no success...
let uuidString = UUID().uuidString
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (5*60), repeats: true)
let request = UNNotificationRequest(identifier: uuidString, content: notification.request.content, trigger: trigger)
// Schedule the request with the system.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error) in
if error != nil {
}
}
Try checking below code, According to my understanding I think you just need to send a notification with same content after a specific time interval
import UserNotifications
struct NotificationHandlerStruct {
static var notifyTimer : Timer?
}
class LocalNotificationHandler: NSObject, UNUserNotificationCenterDelegate
{
static var shared = LocalNotificationHandler()
//MARK: Schedule Notification
func scheduleNotification(Title title: String, Subtitle subtitle: String, BodyMessage body: String) {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
let content = UNMutableNotificationContent()
//adding title, subtitle, body and badge
content.title = title
content.subtitle = subtitle
content.sound = UNNotificationSound.default()
content.body = body
content.badge = 0
content.userInfo = ["type":"calling"]
//getting the notification trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "Call", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
if NotificationHandlerStruct.notifyTimer == nil {
NotificationHandlerStruct.notifyTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
self.sendNotification(NotificationContent: content)
})
}
else{
NotificationHandlerStruct.notifyTimer?.invalidate()
NotificationHandlerStruct.notifyTimer = nil
}
}
//MARK: Repeat Notification
func sendNotification(NotificationContent content: UNMutableNotificationContent) {
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
//getting the notification trigger
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
//getting the notification request
let request = UNNotificationRequest(identifier: "Call", content: content, trigger: trigger)
//adding the notification to notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
//MARK: Stop Timer
func stopTimer() {
if NotificationHandlerStruct.notifyTimer != nil {
NotificationHandlerStruct.notifyTimer?.invalidate()
NotificationHandlerStruct.notifyTimer = nil
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
//displaying the ios local notification when app is in foreground
completionHandler([.alert, .badge, .sound])
}
}
While user open that specific notification just invalidate the timer
or
Please tell me what exactly you are looking for

ApplePaybutton is not functioning (ApplePay integration with Stripe)

I am trying to integrate Applepay using Stripe so that users are able to make easy payment. I use heroku account as a backend server. I could add the ApplePay Button on the UI (Please take a look at My Current Storyboard) and tried to configure a pop up check-out window coming from bottom for users to make payment.
My Current UI
However, even if I click the ApplePaybutton, nothing happens. My goal now is making the checkout window when users click the ApplePay Button My Goal UI.
I assume that func beginPayment() is supposed to be called when the button is pressed but doesn't work. I suspect that if (stripePublishableKey == "") { and codes after that is set incorrectly. Any help would be appreciated!
import UIKit
import Stripe
enum STPBackendChargeResult {
case success, failure
}
typealias STPTokenSubmissionHandler = (STPBackendChargeResult?, NSError?) -> Void
class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {
let stripePublishableKey = "my Stripe PublishableKey"
let backendChargeURLString = "my heroku URL"
let appleMerchantId = "my apple merchand Id"
let shirtPrice : UInt = 1000 // this is in cents
override func viewDidLoad() {
super.viewDidLoad()
//This is the method of making the ApplePayButton( didn't use storyboard)
let button = PKPaymentButton(type: .buy, style: .black)
button.addTarget(self, action: #selector(ViewController.beginPayment(_:)), for: .touchUpInside)
let bw = button.frame.size.width
let bh = button.frame.size.height
let vw = view.frame.size.width
let vh = view.frame.size.height
button.frame = CGRect(origin: CGPoint(x: vw/2 - bw/2, y: vh/2 - bh/2), size: button.frame.size)
view.addSubview(button)
}
//This func is supposed to be called when ApplePayButton is pressed.
func beginPayment(_: UIButton) {
if (stripePublishableKey == "") {
let alert = UIAlertController(
title: "You need to set your Stripe publishable key.",
message: "You can find your publishable key at https://dashboard.stripe.com/account/apikeys .",
preferredStyle: UIAlertControllerStyle.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
return
}
if (appleMerchantId != "") {
let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: appleMerchantId)
if Stripe.canSubmitPaymentRequest(paymentRequest) {
paymentRequest.paymentSummaryItems = [PKPaymentSummaryItem(label: "Cool shirt", amount: NSDecimalNumber(string: "10.00")), PKPaymentSummaryItem(label: "Stripe shirt shop", amount: NSDecimalNumber(string: "10.00"))]
let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
paymentAuthVC.delegate = self
self.present(paymentAuthVC, animated: true, completion: nil)
return
}
} else {
print("You should set an appleMerchantId.")
}
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: #escaping ((PKPaymentAuthorizationStatus) -> Void)) {
let apiClient = STPAPIClient(publishableKey: stripePublishableKey)
apiClient.createToken(with: payment, completion: { (token, error) -> Void in
if error == nil {
if let token = token {
self.createBackendChargeWithToken(token, completion: { (result, error) -> Void in
if result == STPBackendChargeResult.success {
completion(PKPaymentAuthorizationStatus.success)
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
dismiss(animated: true, completion: nil)
}
func createBackendChargeWithToken(_ token: STPToken, completion: #escaping STPTokenSubmissionHandler) {
if backendChargeURLString != "" {
if let url = URL(string: backendChargeURLString + "/charge") {
let session = URLSession(configuration: URLSessionConfiguration.default)
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let postBody = "stripeToken=\(token.tokenId)&amount=\(shirtPrice)"
let postData = postBody.data(using: String.Encoding.utf8, allowLossyConversion: false)
session.uploadTask(with: request as URLRequest, from: postData, completionHandler: { data, response, error in
let successfulResponse = (response as? HTTPURLResponse)?.statusCode == 200
if successfulResponse && error == nil {
completion(.success, nil)
} else {
if error != nil {
completion(.failure, error as NSError?)
} else {
completion(.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "There was an error communicating with your payment backend."]))
}
}
}).resume()
return
}
}
completion(STPBackendChargeResult.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "You created a token! Its value is \(token.tokenId). Now configure your backend to accept this token and complete a charge."]))
}
}