Parse Local Datastore + Network Sync

孤街浪徒 提交于 2019-12-03 20:37:45

Finally I found a way to do it based on this GitHub topic : https://github.com/ParsePlatform/ParseUI-iOS/issues/53

Here is the function I use :

func findObjectsLocallyThenRemotely(query: PFQuery!, block:[AnyObject]! -> Void) {

    let localQuery = (query.copy() as! PFQuery).fromLocalDatastore()
    localQuery.findObjectsInBackgroundWithBlock({ (locals, error) -> Void in
        if (error == nil) {
            println("Success : Local Query", msg: "\(query.parseClassName)")
            block(locals)
        } else {
            println("Error : Local Query", msg: "\(query.parseClassName)", error: error)
        }
        query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
            if(error == nil) {
                println("Success : Network Query", msg: "\(query.parseClassName)")
                PFObject.unpinAllInBackground(locals, block: { (success, error) -> Void in
                    if (error == nil) {
                        println("Success : Unpin Local Query", msg: "\(query.parseClassName)")
                        block(objects)
                        PFObject.pinAllInBackground(objects, block: { (success, error) -> Void in
                            if (error == nil) {
                                println("Success : Pin Query Result", msg: "\(query.parseClassName)")
                            } else {
                                println("Error : Pin Query Result", msg: "\(query.parseClassName)", error: error)
                            }
                        })
                    } else {
                        println("Error : Unpin Local Query", msg: "\(query.parseClassName)", error: error)
                    }
                })
            } else {
                println("Error : Network Query", msg: "\(query.parseClassName)", error: error)
            }
        })
    })
}

TO DO : I need to add the "lastUpdateDate" option to fetch only modified data from network.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!