Xcode , Parse.com - Push notifications don't show on my phone. - xcode

followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts : It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
My phone is recognised by the Parse app, and it sends notifications successfully, but my phone never receives them. I tried this from scratch several times, using several Xcode & Parse Apps.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}

1) Did you allow push notifications from your app project?
2) Do you have the correct build identifiers set in parse and in your app?
I have another delegate method that I don't see in your post.
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings!)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}

Related

iOS Swift app calls the SquarePOS app on iPad -Square app's screen displays briefly then reverts to my screen's calling view controller-did nothing

This app is intentionally tiny - the UI is just a button to initiate the api call. The appDelegate simply shows a console log proving the callback was executed. I did this because I can not get the Square payment system to work even thought the code and url setup etc looks right to me. I am wondering if I misunderstand something in the documentation.
My app ID is: sq0idp-TbgQGqSrC84qkfcXSTntNg
bundleID is: com.craig.POSSDKTest2
My info.plist setup is a screenshot:info.plist and URLScheme setup
My code in the api calling VC:
// ViewController.swift
// POSSDKTest2
//
// Created by Dr Craig E Curphey on 2022-06-14.
//
import UIKit
import SquarePointOfSaleSDK
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}//------------------------------------
#IBAction func doPaymentTapped(_ sender: Any) {
//------ API to Square right here ******-----------------
let callbackURL = URL(string: "POSSDKTest2Scheme://")!
SCCAPIRequest.setApplicationID("sq0idp-TbgQGqSrC84qkfcXSTntNg")
var money: SCCMoney?
do {
// Specify the amount of money to charge - $1.00
let todaysFeePennies = 100
money = try SCCMoney(amountCents: todaysFeePennies, currencyCode: "CAD")
} catch {
print("money conversion failed.")
}
let LoginID = "TestPatient"
//log values used to console:
print("Initiating payment api request")
print("callback: \(callbackURL)")
print("money: \(money!)")
print("LoginID: TestPatient")
print("Creating payment api request")
do
{
let apiRequest =
try SCCAPIRequest(
callbackURL: callbackURL,
amount: money!,
userInfoString: LoginID,
locationID: "",
notes: "TestingSDK2",
customerID: "tester2",
supportedTenderTypes: .all,
clearsDefaultFees: false,
returnsAutomaticallyAfterPayment: false,
disablesKeyedInCardEntry: false,
skipsReceipt: false
)
print("api initiating!")
try SCCAPIConnection.perform(apiRequest)
} catch let error as NSError {
print("Error detected: \(error.localizedDescription)")
}//end API
print("End of payment api function.")
}//------------------------------------
}
Here is my appDelegate code - I just want to see if I get a callback - I'll add the code to process the response later ...
// AppDelegate.swift
// POSSDKTest2
//
// Created by Dr Craig E Curphey on 2022-06-14.
//
var squareTokenID = "not specified - let it fail - I just want a callback!"
import UIKit
import SquarePointOfSaleSDK
#main
class AppDelegate: UIResponder, UIApplicationDelegate {
//-------------------------------------------
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
print("Callback was executed!")
guard SCCAPIResponse.isSquareResponse(url) else {
print("\(SCCAPIResponse.isSquareResponse(url))")
return true
}
do {
let response = try SCCAPIResponse(responseURL: url)
if let error = response.error {
// Handle a failed request.
print(error.localizedDescription)
} else {
// Handle a successful request.
}
} catch let error as NSError {
// Handle unexpected errors.
print(error.localizedDescription)
}
return true
}//-------------------------------------------------------
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}//-------------------------------------------------------
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}//--------------------------------------------------------
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}//---------------------------------------------------------
}
Screenshot of console log from trying to do the api:
Console log
The work environment is Xcode 13.3, Swift, macOSMonterey 12.1 beta, iPad 10.2" (I think) mounted in a Square iPad kiosk with attached card reader, running iOS 15.5.
I would be very happy to send the whole project in a zip file to anyone who would be willing to take a look into why it is failing.

Remote Push notifications actions

I created a code that receive remote push norification, this code is worked ok. Now I need to add two "buttons" that swip left and do a action. I know that this below code is used to indetify the action
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if identifier == "optin1" {
//do something
}
else identifier == "option2" {
//do something
}
completionHandler()
}
But I dont knew how to create the buttons to swip left. How can I do it
This is my AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
// Override point for customization after application launch.
let types:UIUserNotificationType = [.Alert, .Sound, .Badge]
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: types, categories: nil))
initLocationManager()
return true
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
//print(error)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print(deviceToken)
}
func application(application: UIApplication, didReceiveRemoteNotificationuserInfo userInfo: [NSObject : AnyObject]) {
print(userInfo)
}
Update: new version Swift 4 compatible. This example was adapted from this amazing tutorial https://cocoacasts.com/actionable-notifications-with-the-user-notifications-framework
Configure User Notification Center
import UserNotifications
...
UNUserNotificationCenter.current().delegate = self
Define Actions
let actionReadLater = UNNotificationAction(identifier: Constants.Action.readLater,
title: "Read Later",
options: [])
Define Category
let tutorialCategory = UNNotificationCategory(identifier: Constants.Category.tutorial,
actions: [actionReadLater],
intentIdentifiers: [],
options: [])
Register Category
UNUserNotificationCenter.current().setNotificationCategories([tutorialCategory])
Schedule local notifications by instance from an IBAction
// Request Notification Settings
UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
switch notificationSettings.authorizationStatus {
case .notDetermined:
self.requestAuthorization(completionHandler: { (success) in
guard success else { return }
// Schedule Local Notification
self.scheduleLocalNotification()
})
case .authorized:
// Schedule Local Notification
self.scheduleLocalNotification()
case .denied:
print("Application Not Allowed to Display Notifications")
case .provisional:
print("provisional")
}
}
previous version
You can copy&paste this code in didFinishLaunchingWithOptions method:
Create the action
// NOTFICATION
let incrementAction = UIMutableUserNotificationAction()
incrementAction.identifier = "HI_ACTION"
incrementAction.title = "Hi!"
incrementAction.activationMode = UIUserNotificationActivationMode.Background
incrementAction.authenticationRequired = false
incrementAction.destructive = false
Create the category
let counterCategory = UIMutableUserNotificationCategory()
counterCategory.identifier = "HELLO_CATEGORY"
Associate action and category
counterCategory.setActions([incrementAction],
forContext: UIUserNotificationActionContext.Default)
counterCategory.setActions([incrementAction],
forContext: UIUserNotificationActionContext.Minimal)
Registration
let categories = NSSet(object: counterCategory) as! Set<UIUserNotificationCategory>
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: categories)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
The last step is only for demostration
let notification = UILocalNotification()
notification.alertBody = "Hey!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
notification.category = "HELLO_CATEGORY"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
When the app is launched you have to push CMD+L
Here's a link to an example

Cannot convert value of type 'NSData' to expected argument type 'String'

I'm writing codes on swift in XCode. This is the code:
import UIKit
import Foundation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let notificationTypes : UIUserNotificationType = [.Alert, .Badge, .Sound]
let notificationSettings : UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings)
{
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("TOKEN:", deviceToken);
let token = String(data: deviceToken, encoding: NSUTF8StringEncoding);
let myUrl = NSURL(fileURLWithPath: "http://......php?id=" + token);
print("URL:",fileURLWithPath: "http://......php?id=" + token);
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print(error.localizedDescription)
}
/* func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}*/
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
Compiler gives me an error on the func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {" and it says me "Cannot convert value of type 'NSData' to expected argument type 'String'"... but I can't understand the way to solve the problem. So, can somebody help me to correct the error?
var charSet: NSCharacterSet = NSCharacterSet(charactersInString: "<>")
var tokenStr: String = (deviceToken.description as NSString)
.stringByTrimmingCharactersInSet(characterSet)
.stringByReplacingOccurrencesOfString( " ", withString: "") as String
print(deviceTokenString)
Try that
USe this, for sending token to the server. Worked well for me
var token: String = "\(deviceToken)"
let rawtoken = token.stringByReplacingOccurrencesOfString(">", withString: "")
let cleantoken = rawtoken.stringByReplacingOccurrencesOfString("<", withString: "")
var finaltoken = cleantoken.stringByReplacingOccurrencesOfString(" ", withString: "")
Final token is the one that you are supposed to use.
Source was Udemy online courses.
Note that the token is BINARY, so you cannot easily convert it to a string (no UTF8!).
It is a good practice to convert it to hex:
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for var i = 0; i < deviceToken.length; i++ {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Push token: \(tokenString)")

Getting this error when trying to implement Chartboost on Swift xcode?

I have this code to add my AppID and App Signature to my AppDelegate.swift file but I get an error on the last line of code. It says: "Cannot invoke startWithAppId with an argument list of type (String, String, Delegate: AppDelegate). What am I doing wrong? Thanks!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let kChartboostAppID = "5236547547457856858568"
let kChartboostAppSignature = "523525225"
Chartboost.startWithAppId(kChartboostAppID, appSignature: kChartboostAppSignature, delegate: self)
}
I forgot to add the ChartboostDelegate initializer. It works now!

Apple - Provisioning profile + Push Notifications

I followed the guide on Parse.com on how to create a certificate and prepare a provisioning account to accept Push Notifications. When i go to Preferences/Accounts :
It shows on the bottom, but when i try to choose it from the Build Settings Tab, it doesn't show, and i always get this error : "no valid 'aps-environment' entitlement string found for application"
I tried this from scratch several times, using several Xcode & parse Apps, Please help me.
Appdelegate code :
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("MyAppId", clientKey: "MyAppClientKey")
var notificationType: UIUserNotificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
var settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
var currentInstallation: PFInstallation = PFInstallation()
currentInstallation.setDeviceTokenFromData(deviceToken)
currentInstallation.saveInBackground()
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println(error.localizedDescription)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
Have you added the device onto the Development Provisioning Profile, then download and installed it? I got that same error until the device was added.

Resources