如何从Parse

时间:2016-07-30 07:35:38

标签: swift parse-platform nsuserdefaults

我有一个项目,可以在Parse中找到对象作为数组,并在应用程序完成启动时获取它。但是当没有网络连接时它无法获取信息,所以我想使用NSUserDefaults,首先将数据保存到NSUserDefaults,并在离线时从NSUserDefaults获取。 有人能给我一个逻辑的例子吗?

这是我写的代码,我不知道如何在离线时获取它。 我希望从Parse追加数据的数组将是[[String]]。

    let userDefaults = NSUserDefaults.standardUserDefaults
    let query = ClassSub.query()
   query.whereKey("nameOfData", containsString: "testString")
   query!.findObjectsInBackgroundWithBlock { (busObjects: [PFObject]?, error: NSError?) -> Void in
        if error != nil {
            print(error)
        }
        for object in testObjects! {
            let testData = object["arrayData"] as? [[String]]
            for i in 0..<testData!.count {testData
               testArrayappend(testData![i])
                self.userDefaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(testData[i]), forKey: "test-time")
            }
        }
    }

Parse中的数据类型是[[String]],它看起来像[[&#34;一个&#34;,&#34;两个&#34;],[&#34;一个&#34;,& #34;三&#34;],[&#34;一个&#34;&#34; 4&#34;]]

1 个答案:

答案 0 :(得分:1)

我认为使用parse ios SDK本地数据存储更好。本地数据存储允许您将解析对象固定到本地数据库中,然后当您离开网络时,仍然可以从本地数据库获取数据。另一个巨大的优势是saveEventually功能,它允许您在离线时保存对象,然后在上线后立即将它们同步回服务器。

要使用本地数据存储功能,您需要执行以下步骤:

  1. 在解析配置中启用本地数据存储

    let configuration = ParseClientConfiguration {
        $0.applicationId = "{PARSE_APP_ID}"
        $0.server = "http://localhost:1337/parse"
        $0.localDatastoreEnabled = true
    }
    
    Parse.initializeWithConfiguration(configuration)
    
  2. 如果要从本地数据存储区查询(在离线时),只需在调用findObjectsInBackground之前调用其他函数,这样代码应如下所示:

    let query = PFQuery(className: "MyParseObjectClassName")
    
    // if you are in offline mode then make sure the query
    // will access your local data store and not to the server
    if (offlineMode){
        query.fromLocalDatastore()
    }
    
    query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in
    
    
    
        // do something with the result
    
    
    }
    
  3. 使用本地数据存储时,需要固定从服务器获取的对象。为了固定一个对象,只需调用存在于PFObject下的pinInBackground()即可。您还可以使用pinAllInBackground()在一次调用中将多个对象固定到本地数据存储。为了固定您的物体,请执行以下操作:

    let query = PFQuery(className: "MyParseObjectClassName")
    
    // if you are in offline mode then make sure the query
    // will access your local data store and not to the server
    if (self.offlineMode){
        query.fromLocalDatastore()
    }
    
    query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in
    
        if (!self.offlineMode){
            // pin all objects
            PFObject.pinAllInBackground(objects)
    
    
            // pin only first object
            let obj = objects?.first
            obj?.pinInBackground()
        }
    
    }
    
  4. 现在,为了知道您何时离线或在线,我建议您使用Reachability库。 该库为您提供了两个块:当您在线时和离线时。使用这些块可以确定您的应用程序何时连接到互联网以及何时无法连接。因此,当它未连接到互联网时,您需要将offlineMode标志设置为 true ,从现在开始,所有查询都将对您的本地数据库起作用,否则它将对您的服务器起作用。