Set delay for receive notifications and load app swift - ios

colleagues!
Cant find any additional information for catching correctly notifications if app closed.
In my case, when I receive notification, my code just running 1 VC, and can't do anything more. How I can place delay? I mean: first app launch, and after this my notification will be posted.
I can do it with delay and timer, but im trying to do everything clear and correctly.
So, I've got
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
__block AppDelegate * blockSelf = self;
NSString * jsonStrPush = userInfo[#"data"];
NSDictionary *fullDic = [[FrequentRepeateFunc sharedInstance] nsString_to_Dic:jsonStrPush];
NSInteger type = [fullDic[#"push_type"] integerValue];
NSLog(#"PUSH NUMBER %ld", type);
NSDictionary *dataPush = fullDic[#"data"];
NSDictionary *newDataNotification = dataPush [#"notification"];
if(nc != nil){
switch (type) {
They are the same with swift.
and I've got about 50 cases like
case 25: {
NSDictionary *dic = #{#"json": dataPush};
[[NSNotificationCenter defaultCenter] postNotificationName:#"pushFromMap" object:nil userInfo:dic];
}
break;
Next step I got Observer class with NC.Default.addobserver which called some methods like:
#objc func pushFromMap(_ notification: Notification) {
guard let dicData = notification.userInfo?["json"] as? [String: Any] else { return }
guard let name = dicData["user_name"] as? String else { return }
guard let gender = dicData["gender"] as? Int else { return }
let storyboard = UIStoryboard(name: "NewDesign", bundle: nil)
let navContr = UIApplication.shared.windows[0].rootViewController as! UINavigationController
let controller = storyboard.instantiateViewController(withIdentifier: "SameViewController") as! SameViewController
controller.prepareController(parent: navContr, eventId: "", forImage: gender == 1 ? .goodHe : .goodShe, text: name) {}
}
How I can create delay for waiting or conditions to check if app in active mode? THis code works perfect if app is active, or was active 1-2 min ago. But if I close app, this notifications are useless.

Related

Sinch Video Call get Notification for Audio Call

I'm getting "Incoming audio call" however the call is Video
Hint: I'm using (IOS SDK 3.10.1) SDK and SinchService.
here is the code:
func startVideoCall(userId: String, isPrivate: Bool) -> SINCall? {
if let user = User.current {
let callingId = userId
if let callClient = self.callClient() {
let privateString = isPrivate ? VoipCallConstants.Parameters.PrivateTrue : VoipCallConstants.Parameters.PrivateFalse
let headers:[String: String] = [VoipCallConstants.Parameters.Private:privateString]
let call = callClient.callUserVideo(withId: callingId, headers: headers)
return call
}
}
return nil
}
func callClient() -> SINCallClient? {
let appDelegate: AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
return appDelegate.sinch?.callClient()
}
class AppDelegate: UIResponder, UIApplicationDelegate{
var sinch: SINService!
var push: SINManagedPush!
}
and i added in SINSLazyCallClient this
- (id<SINCall>)callUserVideoWithId:(NSString *)userId {
return [self callUserVideoWithId:userId headers:#{}];
}
- (id<SINCall>)callUserVideoWithId:(NSString *)userId headers:(NSDictionary *)headers {
if (self.proxee) {
return [self.proxee callUserVideoWithId:userId headers:headers];
} else {
return [[SINSFailedCall alloc] initWithUserId:userId headers:headers];
}
}
here is Localization.strings
SIN_INCOMING_CALL = "Incoming audio call";
SIN_INCOMING_CALL_DISPLAY_NAME = "Incoming audio call from %#";
SIN_INCOMING_VIDEO_CALL = "Incoming video call";
SIN_INCOMING_VIDEO_CALL_DISPLAY_NAME = "Incoming video call from %#";
Thanks for your feedback. We looked into this and it turned out the support for SIN_INCOMING_VIDEO_CALL and SIN_INCOMING_VIDEO_CALL_DISPLAY_NAME is not implemented in our system yet. We will keep you updated once this is fixed.

Notifications with Swift 2 and Cloudkit

I am making a "texting app" you can call it and it uses cloudkit and I have been looking everywhere to add notifications that work with cloudkit... Would someone be able to tell me the code to add push notifications for cloudkit in detail because I am very lost... Also I wan't the notifications to go to different "texting rooms" (in cloudkit it would be record types...) For instance I have one record type called "text" and another one called "text 2" I don't want notifications from "text" to get to people who use "text2" and vise versa.
Using Swift 2.0 with El Captain & Xcode 7.2.1
Elia, You need to add this to your app delegate. Which will arrive in a userInfo packet of data, which you can then parse to see which database/app sent it.
UIApplicationDelegate to the class
application.registerForRemoteNotifications() to the
func application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Than this method
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
let notification = CKQueryNotification(fromRemoteNotificationDictionary: userInfo as! [String : NSObject])
let container = CKContainer(identifier: "iCloud.com")
let publicDB = container.publicCloudDatabase
if notification.notificationType == .Query {
let queryNotification = notification as! CKQueryNotification
if queryNotification.queryNotificationReason == .RecordUpdated {
print("queryNotification.recordID \(queryNotification.recordID)")
// Your notification
}
}
print("userInfo \(userInfo["ck"])")
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: self, userInfo:dataDict)
}
}
}
}
}
That'll get you started.
You can use this method to check your subscriptions programmatically, of course while your developing you can use the dashboard.
func fetchSubsInPlace() {
let container = CKContainer(identifier: "iCloud.com")
let publicDB = container.publicCloudDatabase
publicDB.fetchAllSubscriptionsWithCompletionHandler({subscriptions, error in
for subscriptionObject in subscriptions! {
let subscription: CKSubscription = subscriptionObject as CKSubscription
print("subscription \(subscription)")
}
})
}
And finally when you got it; you can this routine to ensure you capture any subscriptions you missed while your app was sleeping and make sure that subscriptions don't go to all your devices, once you treated them too.
func fetchNotificationChanges() {
let operation = CKFetchNotificationChangesOperation(previousServerChangeToken: nil)
var notificationIDsToMarkRead = [CKNotificationID]()
operation.notificationChangedBlock = { (notification: CKNotification) -> Void in
// Process each notification received
if notification.notificationType == .Query {
let queryNotification = notification as! CKQueryNotification
let reason = queryNotification.queryNotificationReason
let recordID = queryNotification.recordID
print("reason \(reason)")
print("recordID \(recordID)")
// Do your process here depending on the reason of the change
// Add the notification id to the array of processed notifications to mark them as read
notificationIDsToMarkRead.append(queryNotification.notificationID!)
}
}
operation.fetchNotificationChangesCompletionBlock = { (serverChangeToken: CKServerChangeToken?, operationError: NSError?) -> Void in
guard operationError == nil else {
// Handle the error here
return
}
// Mark the notifications as read to avoid processing them again
let markOperation = CKMarkNotificationsReadOperation(notificationIDsToMarkRead: notificationIDsToMarkRead)
markOperation.markNotificationsReadCompletionBlock = { (notificationIDsMarkedRead: [CKNotificationID]?, operationError: NSError?) -> Void in
guard operationError == nil else {
// Handle the error here
return
}
}
let operationQueue = NSOperationQueue()
operationQueue.addOperation(markOperation)
}
let operationQueue = NSOperationQueue()
operationQueue.addOperation(operation)
}
}

Push notification displaying whole receiving content when is on background

I'm developing a chat app. I'm using apple push notification service to notify user when he receives new messages. There are two scenarios.
The first when user is chatting and receiving a message, the user shouldn't be notified (meaning that notification shouldn't be shown) and when the app is in background i want to alert user for the messages. Everything is ok except that when app is on background the notification shows the whole JSON object the client is receiving.
The idea is ignore visually notification and if its on background show a local Notification.
This is how i have implemented the notification settings
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
let types: UIUserNotificationType = [UIUserNotificationType.None]
let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
//App handle notifications in background state
if application.applicationState == UIApplicationState.Background {
var login_user = LoginUser();
login_user.loadData();
var username:String!;
var message:String!;
if let msg = userInfo["aps"]as? Dictionary<String,AnyObject>
{
if let alert = msg["alert"] as? String{
if let data = alert.dataUsingEncoding(NSUTF8StringEncoding)
{
do
{
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data,options: [])
username = jsonObject["senderUserName"] as! String;
message = jsonObject["content"] as! String!;
DatabaseOperations().insert(DatabaseOperations().STRING_VALUE_CHATING_USERNAME, value: username);
NSNotificationCenter.defaultCenter().postNotificationName("push_notification", object: self)
}
catch
{
}
}
}
}
let localNotification: UILocalNotification = UILocalNotification()
switch(login_user.privacyLevelId)
{
case 1:
localNotification.alertBody = username + ":" + message;
break;
case 2:
localNotification.alertBody = username;
break;
case 3:
localNotification.alertBody = "New Message";
break;
default:
localNotification.alertBody = "New Message";
break;
}
localNotification.alertAction = "Message"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//App is shown and active
else
{
if let msg = userInfo["aps"]as? Dictionary<String,AnyObject>
{
if let alert = msg["alert"] as? String
{
if let data = alert.dataUsingEncoding(NSUTF8StringEncoding)
{
do
{
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data,options: [])
let sender:String = jsonObject["senderUserName"] as! String;
DatabaseOperations().insert(DatabaseOperations().STRING_VALUE_CHATING_USERNAME, value: sender);
NSNotificationCenter.defaultCenter().postNotificationName("push_notification", object: self)
}
catch
{
}
}
}
}
}
}
I set UIUserNotificationType to NONE. Shouldn't by default the notification shows nothing?
I also have read some other posts, but i couldn't find anything to solve the problem.
Why does UIUserNotificationType.None return true in the current settings when user permission is given?
Hide, do not display remote notification from code (swift)
Any help would be appreciated.
application didReceiveRemoteNotification won't be called if the app is closed or in the background state, so you won't be able to create a local notification. So you need to pass the text you want to display in the aps dictionnary, associated with the alert key.
If you want to pass more information for the active state case, you should add them with a custom key to the push dictionnary.
For example :
{"aps": {
"badge": 1,
"alert": "Hello World!",
"sound": "sound.caf"},
"task_id": 1}

Geofencing UILocalNotification not working properly swift

I am facing a strange problem with local notification in swift.
I am presenting local notification like this
let notification = UILocalNotification()
var body = "Hi Krishna";
if(region.identifier == "entry1") {
body += " Welcome";
} else {
body += " Bye! Bye!";
}
notification.alertBody = body
notification.soundName = "Default";
notification.userInfo = ["id": "id"];
notification.fireDate = NSDate(timeIntervalSinceNow: 1)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
and how I am handling launch options in my appdelegate
if(launchOptions != nil) {
window?.rootViewController?.view.backgroundColor = UIColor.cyanColor();
if let notification = launchOptions![UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
window?.rootViewController?.view.backgroundColor = UIColor.blackColor();
if let userInfo = notification.userInfo {
window?.rootViewController?.view.backgroundColor = UIColor.blueColor();
if let id = userInfo["id"] as? String {
window?.rootViewController?.view.backgroundColor = UIColor.redColor();
}
}
}
}
for debugging purpose I am changing the background color of the view.
when I tap to the notification I get the cyan color that means below line is failing
launchOptions![UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification
because I set cyan color right above this line.
so I am not getting why this is not castable to UILocalNotification?
can somebody help me to get rid from this issue?+
one more thing actually if I am doing it normally its working but I am using geofencing and I am scheduling notification from
locationManager(manager: CLLocationManager, didExitRegion region: CLRegion)
In this case its not working.
You could implement application(_:didReceiveLocalNotification:) (which gives you the notification directly) in your AppDelegate and handle the notification there.
More: https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/index.html#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveLocalNotification:
Can you please try to cast like this:
if let notification:UILocalNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
//do stuff with notification
}

how to show push notification in foreground in ios?

my app had a push notifications , can i show the push notification message in alert ?
NOTE:When user click on the notification it will redirect to the application page and notification disappears so here show total notification message in an alert? Is it possible in iOS application?
(void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSString *stringNotify = [NSString stringWithFormat:#"%#",[[[userInfo valueForKey:#"aps"] valueForKey:#"alert"] valueForKey:#"body"]];
NSLog(#"the dictionary is %#",userInfo);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Notification"
message:stringNotify delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
}
I have created a custom Notification, which will help you to show notification when your app is in foreground.
Check the following link iOSForegroundNotification and follow the steps given below:
Copy SNotificationView.h and SNotificationView.m in files in your project.
If you are using swift then add #import "SNotificationView.h" to your Bridging-Header.h file.
Copy "Glass.mp3" file for the notification sound.
You have replace/add you appicon image to "image.png".
You have add the following lines in your AppDelegate file:
let settings = UIApplication.sharedApplication().currentUserNotificationSettings()
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let message = alert["message"] as? NSString {
prefs.setObject(message, forKey: "notification")
prefs.synchronize()
print("Message: \( message)\n")
}
} else if let alert = aps["alert"] as? NSString {
// Push notification message is added in NSUserDefault
prefs.setObject(alert, forKey: "notification")
prefs.synchronize()
if (application.applicationState == UIApplicationState.Active ) {
if settings?.types & UIUserNotificationType.Alert != nil {
// .Alert is one of the valid options
// If you want to add the badge add the line below
UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
//Call the custom Notification
NSNotificationCenter.defaultCenter().postNotificationName("remotenotification", object: nil)
}
else
{
// This part will be called if you app notification is set to "NONE"
print("No alert ")
}
}
}
Add the following function for all your ViewController
func callNotification()
{
let prefs = NSUserDefaults.standardUserDefaults()
let alert = prefs.stringForKey("notification")!
SNotificationView.showNotificationViewWithImage(UIImage(named:"image.png"), title: "XcodeProject", message: alert, isAutoHide: true, onTouch: {
SNotificationView.hideNotificationViewOnComplete(nil)
})
}
Add the following line in your viewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: "callNotification", name: "remotenotification", object: nil)
Hope this might be helpful

Resources