I'm developing iOS application in Unity. I need to show Local Push Notifications.
I use the next code:
public class TestNotification : MonoBehaviour {
void Start(){
UnityEngine.iOS.NotificationServices.RegisterForNotifications(UnityEngine.iOS.NotificationType.Alert | UnityEngine.iOS.NotificationType.Badge | UnityEngine.iOS.NotificationType.Sound);
}
public void ShowNotification(){
#if UNITY_IOS
var iOSNotification = new UnityEngine.iOS.LocalNotification();
iOSNotification.alertBody = "Hello!";
UnityEngine.iOS.NotificationServices.PresentLocalNotificationNow(iOSNotification);
#else
Debug.LogError("Platform is not supported.");
#endif
}
}
When I call ShowNotification, notification appears in Notification Panel, but without any sound and popup. How to make my notifications show normally? I accepted all permissions(alert, sound, badge) on launch.
Testing Device: iPhone 4s, iOS 9.3.5
Build: Unity 5.4.4f1, XCode 8.2.1
You need to place this code in order to play sound and display alert
iOSNotification.soundName = LocalNotification.defaultSoundName;
iOSNotification.alertAction = "Alert Action";
iOSNotification.hasAction = true;
If you wan sound, you should specify default sound name.
iOSNotification.soundName = "default";
Add this, and it will play default sound.
Related
I have an apple watch app that is not independent from the iPhone and I receive push notifications successfully on my watch.
However, tapping the push notification always opens the watch app. I do not want to handle this in the watch app. Is there a way to do this? Is there a way to not open the watch app on tap?
I've tried using the handleAction() functions in the WKExtensionDelegate but these are apparently now deprecated, and they never get fired.
This might not be possible. It relies on the OS.
Possible reasons for this is notifications are for the user to click and open the app usually. And this might go against apple app guidelines too to prevent the app from opening.
However, you can try these:
This is an example of a foreground service with the notification.
public class UploadService extends IntentService{
private NotificationCompat.Builder mBuilder;
public UploadService() {
super("UploadService");
}
#Override
protected void onHandleIntent(Intent intent) {
Intent deleteIntent = new Intent(this, CancelUploadReceiver.class);
PendingIntent pendingIntentCancel = PendingIntent.getBroadcast(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//building the notification
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.ic_menu_upload)
.setContentTitle("Uploading Media...")
.setTicker("Starting uploads")
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Cancel Upload", pendingIntentCancel);
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setProgress(100, 0, true);
startForeground(12345, mBuilder.build());
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You need to register the CancelUploadReceiver in the manifest file.
<receiver android:name=".CancelUploadReceiver"/>
And when the “Cancel Upload” is tapped it will receive the broadcast. Then we can simply stop the service.
public class CancelUploadReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent();
service.setComponent(new ComponentName(context,UploadService.class));
context.stopService(service);
}
}
Another option might be to create a Custom Interface that implements the UINotificationContentExtension protocol.
Related:
Can you disable App-opening mechanism when the user presses the Notification Banner?
How to disable opening app when user tap push notification
iOS notifications actions without opening the app
Is it possible to avoid showing app to user when tapping on a push notification in iOS?
Android notifications actions without opening the app
Andriod notifications with actions
I use Firebase to push notifications to the users at a certain time. They receive the notification but no alert sound is played. In the settings, the allow sound/notifications are turned on and other IOS13 and other apps play sound.
Version Number of FirebasePushNotificationPlugin Plugin: 3.3.10
Device Tested On: iphone X, OS: 13.4.1
Simulator Tested On: N/A (simulators don't receive notifications)
Version of VS: VS for Mac Community, 8.6.6 (build 11)
Version of Xamarin: Xamarin.IOS 13.18.2.1, Xamarin.Forms v4.6.0.847
AppDelegate.cs:
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
bool fbaseStarted = false;
try
{
// This method does all the UNUserNotificationCenter.Current.RequestAuthorization() code so we don't have to.
FirebasePushNotificationManager.Initialize(options, true);
fbaseStarted = true;
}
catch
{ }
LoadApplication(new App());
if (!fbaseStarted)
{
try
{
FirebasePushNotificationManager.Initialize(options, true);
}
catch { }
}
FirebasePushNotificationManager.CurrentNotificationPresentationOption = UNNotificationPresentationOptions.Badge | UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound;
}
Within one of the pages of my code, I subscribe a list of tags (please note that I unsubscribe because the first time the code runs it fails silently if the notifications aren't approved - resulting in the model thinking the notifications was subscribed when it wasn't):
CrossFirebasePushNotification.Current.UnsubscribeAll();
CrossFirebasePushNotification.Current.Subscribe(Constants.NotificationTagsArray);
I keep coming across payload json solutions but unless I am wrong, I don't think that applies to me as I am using Xamarin and the FirebasePushNotificationPlugin. Is there any additional permissions that were added in ios 13 for playing notifications with sound that I have missed?
I have also posted here: https://github.com/CrossGeeks/FirebasePushNotificationPlugin/issues/348 but nobody has been able to assist me yet.
Thanks
The issue actually lies with the sending of the notifications nothing to do with the Xamarin App. The issue resided in the services that sends the notifications to firebase (to then be sent out to the phones).
In the service we were sending a FirebaseNet.Messaging.Message() to the phones:
Message FireBasemessage = new Message()
{
To = "/topics/" + PushNote.Tag,
TimeToLive = 86400,
Priority = MessagePriority.high,
ContentAvailable = true,
Notification = new AndroidNotification()
{
Tag = "/topics/" + PushNote.Tag,
Body = enhancedMessage,
Title = xtitle,
}
,
Data = new Dictionary<string, string>
{
{ "param", PushNote.Tag },
{ "text", enhancedMessage}
}
};
In the AndroidNotification() object required Sound = "default" to be added for it to work. Please note that this works for both Android and IOS notifications despite the fact it is an AndroidNotification object.
i can not show big image in notification in ios when app close or open , but working in android
var display_notification = new firebase.notifications.Notification({
show_in_foreground: true
})
.setNotificationId(notification._notificationId)
.setTitle(notification._title)
.setBody(notification._body)
.setData(notification._data);
if (Platform.OS == "android") {
display_notification.android
.setChannelId("fcm_default_channel")
.android.setSmallIcon("ic_notification")
.android.setBigPicture(notification._data.picture)
.android.setColor("#171551");
} else {
display_notification.ios.addAttachment(
"1",
"https://files.allaboutbirds.net/wp-content/uploads/2015/06/prow-featured.jpg"
);
}
show notification in ios but not display big-image (rich notification )
You can use IOSNotification
iOS specific notification settings.
NOTE: Some of these settings apply only to iOS 9, or iOS 10+.
These are flagged as appropriate.
launchImage returns nullable string;
Gets the launch image to use with the notification.
setLaunchImage(launchImage) returns Notification;
Sets the launch image for the notification.
launchImage : string
Example
notification
.ios.setLaunchImage('notificationimage.png');
Description of IOSNotification
Description of Displaying Notifications
We are using App Center Push Notification and according to the following article https://learn.microsoft.com/en-us/appcenter/sdk/push/xamarin-forms, push notifications can be handled in App.xaml.cs with the use of Push.PushNotificationReceived.
This is actually working ATM, and the method is actually triggered for both background and foreground notifications.
We need to be able to distinguish them. We navigate the user to a specific part of the app whenever they tap on the notification (background) and we can't do the same if the app is already opened (foreground).
I've seen some ways of accomplishing that but they were all specific to the platform (iOS in this case). Is there a way to do the same in the PCL?
I think Xamarin Forms doesn't give an api for us to get the App's state.
You can achieve this by use DependencyService in Xamarin.Forms:
First define a Interface in your PCL project:
public interface IGetAppState
{
bool appIsInBackground();
}
In iOS:
[assembly: Dependency(typeof(GETAppState_iOS))]
namespace App129.iOS
{
public class GETAppState_iOS : IGetAppState
{
public bool appIsInBackground()
{
UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
bool result = (state == UIApplicationState.Background);
return result;
}
}
}
In Android:
[assembly: Dependency(typeof(GETAppState_Android))]
namespace App129.Droid
{
public class GETAppState_Android : IGetAppState
{
public bool appIsInBackground()
{
bool isInBackground;
RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
GetMyMemoryState(myProcess);
isInBackground = myProcess.Importance != Importance.Foreground;
return isInBackground;
}
}
}
And at anywhere you want to know if your app is in background or foreground, you can use:
bool isInBackground = DependencyService.Get<IGetAppState>().appIsInBackground();
I'm developing a swift audio/video and text chat iOS App using AVAudioSession.
Whenever I select to use some Bluetooth devices the sound played on the device is not the App audio stream. They play only the system sound sent by text chat library whenever messages are sent/received instead. It doesn't happen on all Bluetooth devices, on some of them everything works fine. On Builtin Mic and Speaker the App works fine too.
Here are the most important methods from my class to manage the device:
class MyAudioSession
{
private var mAudioSession: AVAudioSession;
init!()
{
self.mAudioSession = AVAudioSession.sharedInstance();
do {
try self.mAudioSession.setActive(false);
try self.mAudioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .AllowBluetooth);
try self.mAudioSession.setMode(AVAudioSessionModeVideoChat);
try self.mAudioSession.setActive(true);
}
catch {
return nil;
}
}
func switchToDevice(device: AVAudioSessionPortDescription!) -> Bool
{
var ret = false;
if (device != nil) {
do {
try self.mAudioSession.setPreferredInput(device);
ret = true;
}
catch {
self.logSwitch(device, error: error);
}
}
return ret;
}
}
I'd like to understand why my App is not working fine on just SOME Bluetooth devices. These same devices work properly on the other Apps on my Cel.
I did another test: I changed all of this for MPVolumeView, and exactly the same issue occurred, so the problem seems to be on audio player.
Could anybody give me a suggestion to fix this ?
Thx.
Jorg,
While this might not be the best answer I have been able to overcome the weird Bluetooth issues. My problem seems to be similar to yours as I too was using:
AVAudioSessionCategoryPlayAndRecord
This was causing issues for me on some Bluetooth devices (not all but some).
What I wound up doing was setting the Category to:
AVAudioSessionCategoryPlayback
Then when ever I needed to record I would switch the Category over to:
AVAudioSessionCategoryRecord
Then back to Playback after completing my recording.
This was the only way at this time I could get a consistent result from switching between the different outputs (Speaker, Headphones, Bluetooth).
Hope that helps some. Guessing this is a bug in the "AVAudioSessionCategoryPlayAndRecord"