NotificationCenter Post request never gets received - swift

I am trying to post a message to an observable in my app but for some reason it doesn't work at all and the only thing I can attribute it to is installing https://bugfender.com/ can anyone tell me what is wrong with this code or how to track down the root cause as there is no error messages at all
Both snippets have been moved to AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.post(name: Notification.Name("TestPost"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: Notification.Name("TestPost"), object: nil)
return true
}
and the receiver functions is
#objc func onDidReceiveData(_ notification:Notification) {
// Do something now
print("XXXXXX received")
}
===== Updating with my actual code for custom capacitor plugin =======
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
... code for receiving notification starts here
NotificationCenter.default.post(name: Notification.Name("TestPost"), object: nil)
... code for receiving notification ends here
return true
}
import Foundation
import Capacitor
#objc(myHelpers)
public class myHelpers: CAPPlugin {
public override func load() {
print("PluginLoaded")
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(handleSignal), name: Notification.Name("TestPost"), object: nil)
}
#objc func handleSignal()
{
print("XX WE RECEIVED AN EVENT AT handleSignal")
notifyListeners(
"myPluginEvent",
data: [:],
retainUntilConsumed: true
)
}
}

You need to register your observer before you post the notification.

Related

Can't get Firebase Dynamic Link

I am following this tutorial from Firebase to implement Direct Links into my app: Firebase Dynamic Links
My code in my app delegate never seems to run properly. When I run the project I am able to use the link and open the app. But none of the print statements will run so I can't tell if it ran successfully or not:
import UIKit
import Firebase
#main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
return true
}
func handleincomingDynamicLink(_ dynamicLink: DynamicLink) {
guard let url = dynamicLink.url else {
print("Thats weird. My dynamic object link has no url")
return
}
print("Your incoming link parameter is \(url.absoluteString)")
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let handled = DynamicLinks.dynamicLinks()
.handleUniversalLink(userActivity.webpageURL!) { dynamiclink, error in
guard error == nil else {
print("Found an error! \(error!.localizedDescription)")
return
}
if let dynamicLink = dynamiclink {
self.handleincomingDynamicLink(dynamicLink)
}
}
return handled
}
#available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
return application(app, open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey
.sourceApplication] as? String,
annotation: "")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?,
annotation: Any) -> Bool {
if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
return true
}
return false
}
// 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.
}
}
Xcode gives me this error after I use the link:
[connection] nw_read_request_report [C1] Receive failed with error "Software caused connection abort"
use below delegate method in SceneDelegate Class:
func scene(_ scene: UIScene, continue userActivity: NSUserActivity)

Function crash in viewController

Hi developers I have this issue with Adobe Audience Manager POD
in my VC I have this
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
ACPAudience.signal(withData: ["ViewedScreen": "ButtonClicked"]) { (response, error) in
if let error = error {
print(error)
} else {
print(response as Any)
}
}
}
every time I run it it crash with this:
dynamic_cast error 2: One or more of the following type_info's has hidden visibility or is defined in more than one translation unit. They should all have public visibility. N20AdobeMarketingMobile6ModuleE, N20AdobeMarketingMobile13ConfigurationE, N20AdobeMarketingMobile22ModuleDetailsInterfaceE.
implementation is correct as far I know
the solution is creating a NSNotification in the app delegate works no crashes or anything weird
code in app delegate is pretty much the same
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector: #selector(getProfileACP2), name: NSNotification.Name(rawValue: "getProfileACP"), object: nil)
}
#objc private func getProfileACP2(){
ACPAudience.signal(withData: ["ViewedScreen": "ButtonClicked"]) { (response, error) in
if let error = error {
print(error)
} else {
print(response as Any)
}
}
}
then on the VC works like this
override func viewDidLoad() {
super.viewDidLoad()
print("getProfileACP")
print("----------------------------------------------")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "getProfileACP"), object: nil)
print("----------------------------------------------")
print("getProfileACP")
}
after calling it seems like it takes some time after giving the response is not immediately

Capacitor PushNotification Callback nor being called

I'm using the push notification plugin on my application and the call back is not working PushNotifications.addListener( 'registration', ( token: PushNotificationToken ) => ...
Has anyone experienced something like this before?
Found the issue... there is a block of code that needs to be changed on the AppDelegate.swift and Podfile files.
AppDelegate.swift:
Change this:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidRegisterForRemoteNotificationsWithDeviceToken.name()), object: deviceToken)
}
for this:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidFailToRegisterForRemoteNotificationsWithError.name()), object: error)
} else if let result = result {
NotificationCenter.default.post(name: Notification.Name(CAPNotifications.DidRegisterForRemoteNotificationsWithDeviceToken.name()), object: result.token)
}
}
}
PodFile:
Add under capacitor_pods:
pod 'Firebase/Messaging'

Push remote notification

I need create in my app a code that receive a remote information and push it to user when app is on background, I read on web that I need to use didReceiveRemoteNotification on appDelegate, to use remote push notication. I read something about and I need keys and certificates, I do not understand how to use didReceiveRemoteNotification
I need to learn about to push remote notification and how to use. I would like a tutorial or example how create it using swift 2.3.
I used this link and I found it the most helpful
http://www.appcoda.com/push-notification-ios/
I used this app for testing
https://itunes.apple.com/us/app/easy-apns-provider-push-notification/id989622350?mt=12
This is the code I have in my AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
registerForPushNotifications(application)
print(UIDevice.currentDevice().identifierForVendor!.UUIDString)
return true
}
func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(
forTypes: [.Badge, .Sound, .Alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("Device Token:", tokenString)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to register:", error)
}

Checking network status in Swift, observer does not get called

I have imported Reachability.h .m files like written here into my Swift project, but observer / event handler will not get called after start, why?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
let hostReachability = Reachability(hostName: "www.apple.com");
hostReachability.startNotifier();
return true
}
func reachabilityChanged(note: NSNotification) { // <- DOES NOT GET CALLED
let reachability: Reachability = note.object as Reachability;
if(reachability.currentReachabilityStatus() != .NotReachable) {
}
}
The Reachability object returned is an autoreleased object , so it has deallocated hence notification is not triggering . You can fix by keeping a strong reference to it.
create a property to hold Reachability object
var reachability:Reachability?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name:kReachabilityChangedNotification, object: nil)
reachability = Reachability(hostName: "www.apple.com");
reachability?.startNotifier();
return true
}
This will fix your problem.
The observer's name is changed from ReachabilityChangedNotification to kReachabilityChangedNotification. Notice the "k"
As mentioned in other answers, you need to maintain a strong reference to the Reachability object. If you aren't checking a particular host, then call reachabilityForInternetConnection:
let internetReachability = Reachability.reachabilityForInternetConnection()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: internetReachability)
internetReachability.startNotifier()
let hasInternet = internetReachability.currentReachabilityStatus().value == 0 ? false : true
// Save to user defaults, log to console, etc.
return true
}
func reachabilityChanged(note: NSNotification) {
var hasInternet = Bool()
if let reachability = note.object as? Reachability {
hasInternet = internetReachability.currentReachabilityStatus().value == 0 ? false : true
}
// Update user defaults, log to console, show error message, etc.
}
For iOS 3+, use below code:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
NotificationCenter.default.addObserver(self, selector: #selector(checkForReachability(notification:)), name: NSNotification.Name.reachabilityChanged, object: nil)
reachability = Reachability.forInternetConnection()
reachability.startNotifier()
return true
}
// MARK:
// MARK: Check Internet Status
func checkForReachability(notification:NSNotification)
{
let networkReachability = notification.object as! Reachability;
let remoteHostStatus = networkReachability.currentReachabilityStatus()
if (remoteHostStatus == NotReachable)
{
print("Not Reachable")
}
else
{
print("Reachable")
}
}