iOS 应用程序在后台时解析查询不返回,由后台获取触发

Parse Query not returning when iOS app is in background, triggered by Background Fetch

使用后台获取我们触发一个方法

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

如果应用程序 运行 在前台或者 phone 处于唤醒状态,这一切都很好而且很漂亮。 但是当 iPhone 是 locked/asleep 时,findObjectsInBackgroundWithBlock 永远不会 returns 任何数据。

这是预期的行为吗?有没有办法确保此查询和其他查询在设备休眠时正常返回?

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

@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];