IOS Background task with specific time interval - iphone

I wanted to call a service with some interval like 24 hour. So if my app is in background also at that time also it should call for that service. I am supporting location updates, so my app will run in background. But i want to know how can i execute some task with time interval without informing user.
Thanks

The best thing I can think of would be to integrate with Parse. There you can set up cloud code that runs in the background at a specific time. You can also schedule push notifications as needed. Otherwise, this is a fairly difficult situation.

You can use NSThread methods to call your service in background after some time interval.
You can follow this link1 or link2 for understanding of thread management.
Hope this will help..

You can use this code in your app delegate didfinishlaunching method
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationDidTimeout:) name:kApplicationDidTimeoutNotification object:nil];
and set timer according to that to perform your task at a particular time

Related

Notify app when iPad date time settings changed

I would like to get notified when ipad's date-time settings is changed. Is there any way for that?.
I am using NSDateFormatter to find whether iPad/iphone time mode is 12 or 24 hr format. NSDateFormatter is seems to take lots of time( seen in time profiling). So I would like to check use it only when settings is changed.
You can do it using two ways:
Implement - (void)applicationSignificantTimeChange:(UIApplication *)application in your app delegate.
Add a observer for UIApplicationSignificantTimeChangeNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(timeChanged:) name:UIApplicationSignificantTimeChangeNotification object:nil];
applicationSignificantTimeChange:
Tells the delegate when there is a significant change in the time.
- (void)applicationSignificantTimeChange:(UIApplication *)application
Parameters
application
The delegating application object.
Discussion
Examples of significant time changes include the arrival of midnight,
an update of the time by a carrier, and the change to daylight savings
time. The delegate can implement this method to adjust any object of
the application that displays time or is sensitive to time changes.
Prior to calling this method, the application also posts a
UIApplicationSignificantTimeChangeNotification notification to give
interested objects a chance to respond to the change.
If your application is currently suspended, this message is queued
until your application returns to the foreground, at which point it is
delivered. If multiple time changes occur, only the most recent one is
delivered. Availability
Available in iOS 2.0 and later.
Declared In UIApplication.h
For more check UIApplicationDelegate_Protocol
How about adding an observer for NSCurrentLocaleDidChangeNotification ? Per Apple, "Re-create any cached date and number formatter objects whenever the current locale information changes."
You may also want to listen to this notification:
NSSystemTimeZoneDidChangeNotification

UIApplicationDidBecomeActiveNotification is called any time?

I use UIApplicationDidBecomeActiveNotification/UIApplicationWillResignActiveNotification pair to compute app running time. in callback of UIApplicationDidBecomeActiveNotification, I record the startTime, and in callback of UIApplicationWillResignActiveNotification, I record endTime.
in most case, I find the running time is correct. but there are some special case in server's log, I find the running time is strange. like the end time is less than start time, or the end time is much more than the start time. so I suspect the UIApplicationDidBecomeActiveNotification is not called in some times. if some one meet such kind of case, and give me some suggestion.
If you are listening for UIApplicationDidBecomeActiveNotification in a view controller, then viewDidLoad is not called until after UIApplicationDidBecomeActiveNotification is posted. So if you register for the notification in viewDidLoad, you'll miss the first notification, which happened before the view gets loaded. So every time your application launches, you'll miss one such notification. All subsequent notifications will be caught though, including returning from background etc.
UIApplicationDidBecomeActiveNotification will be called everytime your application is coming from background to forgnound.means everytime your application is becoming active from a nonactive state.I think that is the reason for the changing time.

UIWebView loadRequest when applicationDidEnterBackground

In my app from applicationDidEnterBackground i want to ask the application for more time to
create a UIWebView and load request with UIBackgroundTaskIdentifier, then in the delegate
method of UIWebView (webViewDidFinishLoad) i want to do a stuff there and show an alert or
notification while the
application is still reining in the background .
so how i can do that?.
Apple's documentation for UIApplication class for beginBackgroundTaskWithExpirationHandler: method says:
You can call this method at any point in your application’s execution.
You may also call this method multiple times to mark the beginning of
several background tasks that run in parallel. However, each task must
be ended separately. You identify a given task using the value
returned by this method.
This method can be safely called on a non-main thread.
So, once web view finish loading in background you can trigger another operation from webViewDidFinishLoad to show alert.
When you receive applicationDidEneterBackground your app is already effectively in the background. At that moment all your networking should be closed and you really shouldn't try to show any alerts or notifications.

How to schedule events programmatically in ios?

I have been tasked to write an app that allows a user to schedule emails to be sent out in future.
The user selects a date time from a date picker, composes the message and recipient and then schedules the event. When the date/time occurs the message is sent out.
Can someone guide me to how to get about scheduling lets say a text message. I know how to send a text message. Just was not sure on the scheduling aspect of things.
Any pointers will be much appreciated.
The first response will technically allow you to establish a timer that will fire every 2.5 seconds, however the original poster asked for a solution that would fire at a specific time. For that you need to use the following method of NSTimer:
- (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats
The first argument is an NSDate indicating when the timer should fire.
The original poster did not specify, but if this is an iOS app then it is important to understand that timers scheduled to fire at a distant date/time will not fire if your app is not the foreground app. In fact there is no way to schedule such an event to occur when your app is in the background on iOS, so you must take that into account.
Here's a snippet of code which sets a one use timer to call self's imageSavedLabelOff: selector with itself (the timer) as the object parameter to the method. The timer schedules the call to be made in 2.5 seconds.
NSTimer *quickie = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:#selector(imageSavedLabelOff:) userInfo:nil repeats:NO];
You may have already found the answer by now but for future visiters like me I would like to suggest an answer- i.e. EventKit :
https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html
You can schedule/fetch events for any time and do your stuff accordingly. Hope this helps somebody.
You should be able to achieve this using NSRunLoop. Check out the Threading Programming Guide.
Apart from the use of NSTimer, you should be aware that sending of the E-Mail can fail for several reasons (no network available and others). Then you need to reschedule the request, maybe give up after 3 retries and notify the user about this.
You can use -
[self performSelector:#selector(myFunc:) withObject:nil afterDelay:5.0];

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.