I use UserNotifications make a simple notification for test, I wrote the code in AppDelegate as below, when the notification fired in background, it will shows the message on the screen, but it doesn't run the code both print(...) and a.get()) :
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: #escaping () -> Void) {
print("run in didReceive")
let a = ViewController()
a.get()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("granted")
}else{
print("not granted")
}
})
UNUserNotificationCenter.current().delegate = self
return true
}
I just only want to run a "viewcontroller" function when the app when in background...
One problem is this line:
let a = ViewController()
You are creating a "loose" view controller and then throwing it away. What you probably want is a reference to some existing view controller that is already in the interface.
A broader problem might be a false assumption about what userNotificationCenter(_:didReceive:withCompletionHandler:) is for. It is not called to indicate that a notification alert appeared (i.e. the notification fired). It is called to indicate that the user interacted with the notification, such as tapping or (if so configured) dismissing the alert. A banner alert that just appears and goes away again, with no user interaction, will not cause userNotificationCenter(_:didReceive:withCompletionHandler:) to be called.
Related
I'm trying to build a simple webView application for MacOS, but it doesn't seem to work. I've linked the code to the storyboard, imported WebKit, but nothing seems to work. After I finish the build, and try to test it, the window keeps gray. There are no errors involved. Does anyone know what I did wrong?
CODE:
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.mainFrame.load(URLRequest(url: URL(string: "http://apple.com")!))
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
You should be using a WKWebView instead of a WebView. WKWebView replaced WebView in macOS 10.10.
#IBOutlet var webView: WKWebView?
To load a webpage create a URL request with the webpage's URL. Call the web view's load() function to load the webpage with the URL request. The following code should load Apple's website in a WKWebView:
override func viewDidLoad() {
super.viewDidLoad()
loadWebContent()
}
func loadWebContent() {
if let myURL = URL(string: "https://www.apple.com") {
let myRequest = URLRequest(url: myURL)
webView?.load(myRequest)
}
}
One last thing you have to deal with is the app sandbox. Xcode projects initially have the app sandbox turned on. The app sandbox is set initially to disallow any incoming and outgoing network connections. Either allow incoming and outgoing network connections or turn off the sandbox.
I have my app in Expo pushing a notification when somebody sends a message, but if that person sends multiple messages a second notification is pushed.
Is there anything I can do to clear the previous notification, or simply update the notification instead of adding a second notification to the list?
Basically I need to force an override or dismiss previous notifications.
The approach I was hoping to use was to add a listener which cleared notifications before appending, but it seems that this only works when the app is in the foreground.
Is there a recommended approach to this currently?
You can clear any or all previous notifications in expo-notifications. Your question is not clear but I am guessing you want to clear all previous notification if new notification is received. You have to spot the best place when to clear notifications on your code. But here are some tips (use the following code in the useEffect hook) -
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
responseListener.current =
Notifications.addNotificationResponseReceivedListener((response) => {
// DISMISS ALL NOTIFICATION AFTER INTERACTION
Notifications.dismissAllNotificationsAsync();
});
If you want to dismiss specific notification in that case, use dismissNotificationAsync(identifier: string): Promise method.
Just in case, if you want to dismiss all notifications when receiving a new one while the app is foregrounded (use the following code in the useEffect hook).
// This listener is fired whenever a notification is received while the app is foregrounded
notificationListener.current =
Notifications.addNotificationReceivedListener((notification) => {
// setNotification(notification);
// DISMISS ALL NOTIFICATION UPON RECEIVING NOTIFICATION WHILE IN FOREGROUND
Notifications.dismissAllNotificationsAsync();
});
You can use Notifications.dismissAllNotificationsAsync() method or dismissNotificationAsync(identifier: string): Promise method anywhere you like but you need to spot where to best use them.
_handleNotification = (notification) => {
this.setState({notification: notification});
console.log('get notification', this.state.notification);
let localnotificationId = this.state.notification.notificationId;
setTimeout(function () {
Notifications.dismissNotificationAsync(localnotificationId);
}, 10000)
};
This is how I do in NodeJS
I have an application and PUSHs work fine when the app is on background I tap on push notification and it redirects me - OK.
But here is the situation which i have to fix:
1 step: I open the app, working with it, it is active
2 step: notification comes but user is not seeing anything AND he gets redirected to another ViewController(according to push notification info) UNEXPECTEDLY.
I need the app NOT to redirect anywhere when it is active unless the push notification is actually tapped.
I found a solution!
in didReceiveRemoteNotification method add if statement:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if application.applicationState == .inactive || application.applicationState == .background {
//here add you actions
}
}
By setting breakpoints, i noticed that the handler was getting called when the app is exiting.
Am I doing something wrong? If not, why would branch want to do this?
// This is in app delegate
branch.initSessionWithLaunchOptions(launchOptions, automaticallyDisplayDeepLinkController: true, deepLinkHandler: { params, error in
// breakpoint
if error == nil {
self.handleDeepLink(params)
}
else {
error?.showInToast()
}
})
}
Alex from Branch here: this is not expected behavior from our SDK. Are you overriding any of the other app lifecycle methods (e.g., applicationDidBecomeActive or applicationWillResignActive)?
I have create an application which is sending data to watch for showing.
When the watch is screen is active then it sending data perfectly, but when watch sleeps then an error occurred that device is not active.
My question is that when the watch is active any how it will get that data which send via using WKSession sendMessage method from my iPhone?
If the watch screen is off, the calling sendMessage on the iPhone won't work. You can only send data in real time when the watch screen is on. This is different than when you are using sendMessage from the watch to the iPhone (iPhone screen can be off). This is the block of code I use anytime I call sendMessage from my iPhone code:
// Send messages to any paired apple watch.
func tryWatchSendMessage(message: [String : AnyObject]) {
if self.session != nil && self.session.paired && self.session.watchAppInstalled {
self.session.sendMessage(message, replyHandler: nil) { (error) -> Void in
// If the message failed to send, queue it up for future transfer
self.session.transferUserInfo(message)
}
}
}
Then I setup the apple watch app to have the same handler if it gets the data via sendMessage or transferUserInfo.