Reputation: 345
Using a Background Fetch we trigger a method
- (void)sendPush:(SPUserInfo *)userInfo {
PFQuery *findUserQuery = [PFUser query];
[findUserQuery whereKey:@"objectId" equalTo:userInfo.userID];
[findUserQuery findObjectsInBackgroundWithBlock:^(NSArray* arr, NSError* err) {
if (err) {
MLog(@"Error Finding User to Spark: %@", err.description);
}
else {
if (arr.count) {
MLog(@"User found");
PFObject *spark = [PFObject objectWithClassName:kSparkClassName];
[...]
[spark saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
//save
// send push through Parse
[...]
PFPush *push = [PFPush push];
NSString *channel = [NSString stringWithFormat:@"u_%@", receiver.objectId];
[push setChannels:@[channel]];
[push setData:data];
[push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (nil == error) {
MLog(@"Push success");
//do the stuff
[self.queueSendingSpark removeObject:userInfo];
[self saveSendingSparkQueue];
}
else {
MLog(@"Push Error : %@", error.description);
}
}];
}
else {
MLog(@"Spark is not saved on parse | %@", error);
}}];
}
else {
MLog(@"ZERO Users");
}
}
}];
}
This is all fine and dandy if the app is running in the foreground or if the phone is awake. But when the iPhone is locked/asleep, the findObjectsInBackgroundWithBlock
never returns any data.
Is this expected behaviour? Is there a way to ensure this query, and others, are returning as normal when a device is asleep?
Upvotes: 0
Views: 327
Reputation: 1632
So theres a property that you can use to handle this...
@property (nonatomic, assign) UIBackgroundTaskIdentifier fileUploadBackgroundTaskId;
Within your init method set the property like so:
self.fileUploadBackgroundTaskId = UIBackgroundTaskInvalid;
Set the value when needed
// Request a background execution task to allow us to finish uploading the photo even if the app is backgrounded
self.fileUploadBackgroundTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.fileUploadBackgroundTaskId];
}];
Run your query, then when the query is finished...
[[UIApplication sharedApplication] endBackgroundTask:self.fileUploadBackgroundTaskId];
Upvotes: 1