This is my code to save data to parse localDatastore in swift
@IBAction func addMessage(sender: AnyObject) {
var newMessage = addMessageText.text
let message = PFObject(className: "Messages")
var user = PFUser.currentUser()
message["messageTextColumn"] = newMessage
message["user"] = user!.objectId
message.saveInBackgroundWithBlock {(success: Bool, error: NSError?) -> Void in
if (success) {
println("added to Message Class")
println(user)
message.saveInBackground()
} else {
// Error saving message
}
}
}
and this is how I query for that data in messagesListController Class
@IBOutlet var messageTableView: UITableView!
var messageArray:[String] = ["Lope"]
override func viewDidLoad() {
super.viewDidLoad()
retrieveMessagesLocally()
retrieveMessages()
}
func retrieveMessagesLocally(){ // function that query the message data from parse local datastore
let query = PFQuery(className: "Messages")
query.fromLocalDatastore()
var currentUser = PFUser.currentUser()
query.whereKey("user", equalTo: currentUser!.objectId!)
query.findObjectsInBackground().continueWithBlock {
(task) -> AnyObject in
if let error = task.error {
println("Error: \(error)")
return task
}
println("Retrieved \(task.result.count)")
return task
}
}
func retrieveMessages() {
var query = PFQuery(className:"Messages")
var user = PFUser.currentUser()
query.whereKey("user", equalTo:user!.objectId!)
query.findObjectsInBackgroundWithBlock { [weak self]
(objects:[AnyObject]?, error:NSError?) -> Void in
println(objects)
println("succeed")
let messages = objects
for object in objects!{
if let message = object["messageTextColumn"] as? String {
println(object)
self?.messageArray.append(message)
}
}
self?.tableView.reloadData()
}
}
The problem is when I try to open message tableview cell without internet connection the message that I saved didn't appear in message tableview cell at all and it seems that it didn't save the data into the parse local datastore as well.
Any help is appreciated.
Thanks!
Your addMessage
method never saves the object to the local datastore, it only saves it to the server, you should call pinInBackground
as well to actually store the object(s) in the local datastore, it is described in the Local Datastore documentation .
You can store a PFObject in the local datastore by pinning it. Pinning a PFObject is recursive, just like saving, so any objects that are pointed to by the one you are pinning will also be pinned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.