Cancel single UILocalNotification - swift

I have several notifications on my app. What i want to do is to, when a local notification arrived, it erases another previous already showed one from notification center.
I am using the the following code.
static func unscheduleNotification(userInfoValue: String){
if let notifications = UIApplication.sharedApplication().scheduledLocalNotifications{
for notification in notifications{
if let userInfo = notification.userInfo as? [String:String]{
if userInfo["info"] == userInfoValue{
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
}
}
}
}
Would appreciate if someone point me out the right direction here. If that is even possible.

I found the solution. Or one solution. Adding one repetition interval to the notification allows with the method i was using and posted on the question to delete it.
I don´t know if it is the correct procedure or not but it is indeed working.

If you want to receive 1 notification when getting another 1, then best idea to keep you 1st notification object in NSUserDefault, when getting another 1 notification, fetch already stored notification from NSUserDefault then remove it.
Consider example if your device is restarted after receiving 1st notification. then it will be in notification tray but you would not get object to cancel it.
Also scheduledLocalNotifications will not provide object after restating your device. scheduledLocalNotifications doesn't work properly always with iOS 8.
Refer - iOS 8 [UIApplication sharedApplication].scheduledLocalNotifications empty
While storing in NSUserDefault you have to convert notification object to NSData
let data = NSKeyedArchiver.archivedDataWithRootObject(notificationObject)
At the time of getting from NSUserDefault it will be NSData
So again convert to object
let notificationObject : UILocalNotification = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? UILocalNotification

Related

Swift 4 save CBPeripherals array save state when returning to controller [duplicate]

This question already has an answer here:
BLE Peripheral disconnects when navigating to different ViewController
(1 answer)
Closed 5 years ago.
So I am working with Bluetooth connections and I have an array of connected devices (some sensors). The problem in the devices is that, whenever there is something connected to that devices, CBCentralManager scanning doesnt find them (thats how they work). That's why I have to make an array of CBPeripherals that are connected an I want to display it in TableView where I display also not connected devices (the ones found while scanning).
Now, the problem is, whenever I put something into my connectedDevices:[CBPeripheral] array and I go back from my controller, and than return to it, the connectedDivecies array is empty. Thats absolutely normal and I understand it.
So the question is, how can I, in swift, store that array so whenever I return to that controller it holds same data, I mean - same CBPeripheral objects? I tried to do it with UserDefaults but nothing seems to work.
Please give me some ideas on how to manage that
Just keep your devices list in the AppDelegate
then access it using something like
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
Although there is a lot of discussion on whether to use App Delegate as A singleton for storing your objects.
IMHO storing an array of objects that's small won't harm your app anyway

Core Data detail view Error

I have been working on an app that has a tableview where users can add information on a seperate ViewController via UITextField. I am now trying to set it up so the user can tap on any given Cell to be able to view the data back on that ViewController or edit it again. Everything is being saved using CoreData.
Best way is you can put the check like this. So that it will never crash or throw the error:-
if let sender = sender as? String {
guest.player = sender
}

WKInterfaceLabel.setText not reflecting changes following modal viewController dismissal

I am working on a simple video game for the Apple Watch. In awakeWithContext() I call my own method, startNewGame(), and register for it to be called again when receiving a notification from my modal viewController. This all works fine. Then upon determining the game is over, I call self.presentControllerWithName().
When that controller is dismissed by the player I call self.dismissController(). Then I fire a notification that once again calls startNewGame(). This is where things get weird.
self.score = 0
let scoreString = formatScore(0) //"0000"
self.scoreboard.setText(scoreString)
let hiScore = NSUserDefaults.standardUserDefaults().integerForKey("hiScore")
let hiScoreString = formatScore(hiScore)
self.hiScoreboard.setText(hiScoreString)
The above excerpt from startNewGame() shows me resetting the score and updating both "scoreboards" both WKInterfaceLabels that present scores in a skeumorphic old-timey LCD fashion. Because of this, I call formatScore() which returns a string with leading zeros. Anyway, I then set the text on them both and… nothing happens. Both boards show the same score as before the game over view controller was shown. It is only when they are next updated in response to player's actions that they update to reflect the correct values. Because I only have issues with this when the code runs shortly following the dismissal of a modal viewController, I suspect there is some connection. Anyway, I am stumped, some help would be much appreciated.
I ran into the same problem receiving data from the iPhone using sendMessage.
My code was pretty straight forward:
dispatch_async(dispatch_get_main_queue(),{
if let error = error {
NSLog("showing error: \(error)");
self.lblTitle.setText("Error...");
}
});
For me, the message was being logged, but the interface wasn't getting updated.
Ends up I was showing multiple pages using reloadRootControllersWithNames and when I tried to update a label within a page that wasn't being shown, the update was ignored.
I fixed it by listening to willActivate and didDeactivate to see whether to update the label or whether to save the text so I could apply it when the page is shown.
Apparently this is by design.

uilocalnotification programmatically in swift

In my project file, I have two seperate UITableViewCells. One containing a UITextfield and the other containing a UIDatePicker. Both of these cells are placed into a UITableViewController to contain them in a table format. I want a local notification to be sent when the user inputs text and sets a date, but so far I haven't been able to find the right tutorial on this topic using Swift programmatically.
First, create your instance of UILocalNotification: var myNotification = UILocalNotification() Next, give the notification it's text: myNotification.alertBody = "I am a notification!" Next, set a NSDate for when the notification should fire: myNotification.fireDate = NSDate() Finally, add your notification to your app: UIApplication.sharedApplication.scheduleLocalNotification(myNotification) And you should be all set! It should be noted that your UILocalNotification will only fire if your app is not in the foreground (in other words, you can't be in the app). Hope this helped!

MPMediaLibraryDidChangeNotification called twice?

My app uses the iPodMusicPlayer and, when suspended, the user might go out and make changes in Apple's Music App, for example creating or modifying a Playlist, then return to my App.
I receive the expected MPMediaLibraryDidChangeNotification, which is fine and I deal with it updating my references etc., but I receive a second MPMediaLibraryDidChangeNotification about 2 minutes later which I really don't need.
Any ideas on avoiding this second notification?
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(notification_iPodLibraryDidChange:) name: MPMediaLibraryDidChangeNotification object:nil];
[[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];
The notification can be called multiple times depending on what's going on. For example, if you add an album to your phone with 12 songs in it, the notification gets called 12 times. Basically it gets called every time the library changes and not just when the sync has finished (at least on iOS 5.1, not sure about older iOS versions).
Where are you adding he observer? For example, if you add in the viewWillAppear and only remove observers in dealloc, you may have multiple observers which is causing a problem. At least, when I encountered a problem like this it was because I had inadvertently added a second observer without removing all the previous.
2 minutes seems like a long lag time (mine was a few seconds), but still may be worth checking out.
Probably the best way to avoid multiple launches of update procedures after multiple notifications is to set a timer and wait some seconds before performing the actual update.
if( !self.lastModifiedDate ) self.lastModifiedDate = [[NSDate alloc] init];
if( [self.lastModifiedDate compare:[[MPMediaLibrary defaultMediaLibrary] lastModifiedDate]] == NSOrderedSame ) return;
self.lastModifiedDate = [[MPMediaLibrary defaultMediaLibrary] lastModifiedDate];
The above lines in my notification handler method deal with the extra call. Still no idea why I'm getting it.
Remove the beginGeneratingLibraryChangeNotifications command, and it will fix it. :) You just get every notification for changed, one from the notification center, and one from the default library.