保存以在查询数据后手动解析

时间:2015-08-14 11:42:05

标签: ios swift parse-platform

我正在使用Parse pinInBackground功能在背景中固定数据(图像,文本,日期,坐标),每次打开应用程序时都会查询数据。应用程序用于记录照片以及位置和坐标。因此,您查询的每个条目都会在表格视图中显示(仅显示条目数)。 我希望能够让用户手动使用Parse.com下沉,而不是使用saveEventually功能。 意思是我想要一个按钮,当按下时,查询的数据必须与Parse一起下沉并且被固定。 以下是我的数据固定方式

@IBAction func submitButton(sender: AnyObject) {

    locationLogs["title"] = log.title
    locationLogs["description"] = log.descriptionOf
    println("log = \(log.title)")
    println("log = \(log.descriptionOf)")
    locationLogs.pinInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
        if (success) {

        }else{
         println("error = \(error)")
        }}
 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    let location:CLLocationCoordinate2D = manager.location.coordinate
    let altitude: CLLocationDistance = manager.location.altitude

    println("new long= \(location.longitude)")
    println("new lat= \(location.latitude)")
    println("new altitude= \(altitude)")
    println("new timestamp = \(timestamp)")

    locationLogs["longitude"] = location.longitude
    locationLogs["latitude"] = location.latitude
    locationLogs["altitude"] = altitude
    locationLogs["timestamp"] = timestamp


}

在这里我查询它

var result : AnyObject?

override func viewDidLoad() {
    super.viewDidLoad()

    let query = PFQuery(className:"LocationLogs")
    query.fromLocalDatastore()


    query.findObjectsInBackgroundWithBlock( { (NSArray results, NSError error) in
        if error == nil && results != nil {

           self.result = results
            println("count = \(self.result!.count)")
            self.loggedItemsTableView.reloadData()
        }else{
            println("ERRRROOOORRRR HORROOORRR= \(error)")
        }
    })

}

我试过使用这个命令:

 result?.saveAllInBackground()

但这只是给了一个错误。 有人可以给我正确的代码,如何做到这一点,或给我一个链接,告诉我如何。

3 个答案:

答案 0 :(得分:1)

使用它来安全地投射/检查你的对象

<a href="#lorem1">Go to Lorem #1</a>
<br/>
<a href="#lorem2">Go to Lorem #2</a>
<br/>
<a href="#lorem3">Go to Lorem #3</a>
<br/>

<div>
  <h3 id="lorem1"><b>Lorem Paragraph #1</b></h3>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque a tortor vulputate ante ultricies sodales pretium quis augue. Suspendisse quis enim dignissim, pretium elit sit amet, vestibulum elit. Etiam non consectetur ante, sed volutpat mauris. Fusce
  vestibulum orci ligula, sit amet dapibus quam laoreet id. Aenean dignissim, felis quis consectetur rhoncus, est quam volutpat ex, at interdum nisi ligula ac arcu. Suspendisse potenti. Aenean tincidunt maximus nisl, vel congue ipsum viverra vel. Suspendisse
  eget magna eu purus sagittis luctus. Maecenas eleifend at neque at ullamcorper. Nullam semper elit augue, eu pretium tortor congue quis. Morbi gravida semper odio. Duis faucibus ut eros nec suscipit. Proin diam nibh, efficitur at efficitur nec, posuere
  id lacus. Quisque vel tortor vehicula, efficitur mi eget, volutpat nunc. Aenean porta orci at malesuada luctus.

</div>
<br/>
<br/>
<br/>
<div>
  <h3 id="lorem2"><b>Lorem Paragraph #2</b></h3>
  In hac habitasse platea dictumst. Nulla sem magna, cursus in elementum in, ultricies vel velit. Mauris lacinia maximus metus sit amet iaculis. Fusce sed magna tempus, semper ligula ornare, sodales nisl. Vestibulum id neque ut erat pharetra mattis eu sit
  amet nibh. Vivamus ornare justo semper mi fringilla feugiat. Donec ultrices velit dui, a mollis sapien suscipit id. Maecenas congue urna vel justo pulvinar lacinia. Nam non diam commodo, ultricies nulla molestie, dapibus mi. Fusce in lacus sem. Donec
  nisl enim, ullamcorper sit amet rutrum vulputate, pretium at sapien. Nullam vitae tincidunt sapien, sed sollicitudin magna.

</div>
<br/>
<br/>
<br/>

<div>
  <h3 id="lorem3"><b>Lorem Paragraph #3</b></h3>
  Donec tempor ullamcorper quam, eu fringilla diam egestas ut. Etiam eros purus, scelerisque vitae elit id, consectetur congue magna. Etiam in neque quis mauris scelerisque efficitur. Cras et sapien justo. Nam sed ligula metus. Vestibulum gravida eros id
  mi dapibus dapibus. Aliquam lectus dolor, pulvinar vel magna et, rutrum vehicula ante. Pellentesque nisi ipsum, sodales nec dolor id, sodales varius magna. Donec feugiat placerat egestas. Morbi quis magna nec velit auctor bibendum. Vivamus metus magna,
  pellentesque sit amet est ut, dapibus hendrerit risus. Proin vel nulla lacus. Proin lacinia felis sit amet augue dictum, sit amet aliquam velit posuere. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed ac justo justo.



</div>

答案 1 :(得分:1)

struct log {
// this is dummy datastructure that imitate some part of your code ... you dont need it
var title = ""
var descriptionOf = ""
}

struct LocationInfo{

var title:String!
var description:String!
var location:PFGeoPoint!
var timestamp:NSDate!
var username:String

}

var locationManager = CLLocationManager()
 var arrayOfLocations = [LocationInfo]()

func submitButton(sender: AnyObject) {
var logData = log()

var point = OneLocation(locationManager)
let username = PFUser.currentUser()?.username
var locationLogs = PFObject(className: "")
locationLogs["title"] = logData.title
locationLogs["description"] = logData.descriptionOf
locationLogs["Location"] = point
locationLogs["username"] = username
locationLogs["TimeStamp"] = locationManager.location.timestamp
locationLogs.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in
    if error == nil
    {
      println("data was save")
    }
}

}

 func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

CLGeocoder().reverseGeocodeLocation (manager.location, completionHandler: {(placemarks, error)->Void in

    var UserCurrentLocation:CLLocationCoordinate2D = manager.location.coordinate
    // println("User's parking Location : \(UserCurrentLocation.latitude) \(UserCurrentLocation.longitude)")

    if (error != nil) {
        println("Error")
        return
    }
    locationManager.stopUpdatingLocation()

})
}

func OneLocation(Manager:CLLocationManager)->PFGeoPoint{
    var latitude = Manager.location.coordinate.latitude
    var longitude = Manager.location.coordinate.longitude
    var point  = PFGeoPoint(latitude: latitude, longitude: longitude)
    return point

  }

func QueryFromParse(){
var query = PFQuery(className: "")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
    if error == nil
    {
        if let new_objects = objects as? [PFObject]
        {
            for SingleObject in new_objects
            {
                // with this single object you could get the description, title , username,etc
                var location = SingleObject["Location"] as! PFGeoPoint
                var username = SingleObject["username"] as! String
                var title = SingleObject["title"] as! String
                var time = SingleObject["TimeStamp"] as! NSDate
                var description = SingleObject["description"] as! String

                var singleLocationInfo = LocationInfo(title: title, description: description, location: location, timestamp: time, username: username)
                arrayOfLocations.append(singleLocationInfo)
                // reload data for the tableview

            }

        }

    }
    else
    {
      println("error")
    }
  }

}

  

因此,您有一个arrayoflocations可用于填充tableView中的数据   结构日志是虚拟数据结构   而且我也不知道这是不是你想要的......但是你应该明白这个想法......   希望有所帮助..

答案 2 :(得分:1)

以下是关于我如何解决它的完整代码说明:

//create an Array 
var tableData: NSArray = []

func queryAll() {
    let query = PFQuery(className:"LocationLogs")

    query.fromLocalDatastore()
    query.findObjectsInBackgroundWithBlock( { (NSArray results, NSError error) in
        if error == nil && results != nil {
            println("array = \(results)" )
            self.tableData = results!
            self.loggedItemsTableView.reloadData()
        }else{
            println("ERRRROOOORRRR HORROOORRR= \(error)")
        }
    })
}

 //Call save on the class and not the object 
 PFObject.saveAllInBackground(self.tableData as [AnyObject], block: { (success: Bool, error: NSError?) -> Void in
        if (success) {


            //Remember to unpin the data if it will no longer be needed
            PFObject.unpinAllInBackground(self.tableData as [AnyObject])

            println("Pinned Data has successfully been saved")

        }else{
            println("error= \(error?.localizedDescription)")
        }
    })