当iOS应用程序处于后台时,Parse Query不会返回,由Background Fetch触发

时间:2015-01-09 17:20:28

标签: ios objective-c parse-platform

使用背景提取我们触发方法

- (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");
            }
        }
    }];
}

如果应用程序在前台运行或手机处于唤醒状态,这一切都很好。 但是当iPhone被锁定/睡着时,findObjectsInBackgroundWithBlock永远不会返回任何数据。

这是预期的行为吗?有没有办法确保此查询以及其他人在设备处于睡眠状态时正常返回?

1 个答案:

答案 0 :(得分:1)

所以你可以使用一个属性来处理这个......

@property (nonatomic, assign) UIBackgroundTaskIdentifier fileUploadBackgroundTaskId;

在init方法中设置属性如下:

self.fileUploadBackgroundTaskId = UIBackgroundTaskInvalid;

在需要时设置值

// 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];
}];

运行查询,然后查询完成...

[[UIApplication sharedApplication] endBackgroundTask:self.fileUploadBackgroundTaskId];