Is there a way to convert a PFObject from Parse into JSON? I saved as JSON, but when I try to load I'm getting [AnyObject] back. Casting to JSON won't work:
class func loadPeople() -> [String : Person] {
var peopleDictionary: [String : Person] = [:]
let query = PFQuery(className: "userPeeps")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
//this only returns the first entry, how do I get them all?
if let peopleFromParse = objects?.first?.objectForKey("userPeeps") as? JSON {
for name in peopleFromParse.keys {
if let personJSON = peopleFromParse[name] as? JSON,
let person = Person(json: personJSON) {
peopleDictionary[name] = person
}
}
}
below is my save function, which works and saves the JSON into Parse like I want:
class DataManager {
typealias JSON = [String: AnyObject]
class func savePeople(people: [String : Person]) {
var peopleDictionary = people
var peopleJSON: JSON = [:]
for name in peopleDictionary.keys {
peopleJSON[name] = peopleDictionary[name]!.toJSON()
}
let userPeeps = PFObject(className: "userPeeps")
userPeeps.setObject(peopleJSON, forKey: "userPeeps")
userPeeps.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
println("Object Uploaded")
} else {
println("Error: \(error) \(error!.userInfo!)")
}
}
}
So the answer (as Paulw11 points out above) is that "objects" is sort of a wrapper for the real data, so it was necessary to iterate through the array and store each value as JSON:
var peopleDictionary: [String : Person] = [:]
//1 load the dictionary of JSON for key people from Parse
let query = PFQuery(className: "userPeeps")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if let unwrappedObjects = objects {
for object in unwrappedObjects {
if let peopleFromParse = object as? JSON {
for name in peopleFromParse.keys {
if let personJSON = peopleFromParse[name] as? JSON,
let person = Person(json: personJSON) {
peopleDictionary[name] = person
}
}
}
}
}
Related
JSON :
{
"11/08/22":[
{
"Bill Gates":"Microsoft",
"Steve Balmer":"Microsoft"
}],
"13/08/22":[
{
"Tim Cook":"Apple",
"Jony Ive":"Apple"
}]
}
Swift Code :
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
print(jsonResult)
//Get Result into Seperate Arrays
let keys = jsonResult.flatMap(){ $0.0 as? String }
let values = jsonResult.flatMap(){ $0.1 as? String }
}
} catch let error as NSError {
print(error)
}
})
jsonQuery.resume()
Requirements :
If i pass from program "11/08/22", I should be able to get all keys and values in the form of Array of String of only that array named "11/08/22" .
Better Explanation :
It should go into 11/08/22 and it should retrieve "Bill Gates","Steve Balmer" as Keys and "Microsoft" As a value in two separate arrays
For this example let's use an array to collect the people and a set to collect the companies:
var people: [String] = []
var companies: Set<String> = []
Subscript to the JSON dictionary with your "11/08/22" key and cast the result as an array of dictionaries.
Loop over this array and in the loop, add the keys to the people array and insert the values in the companies set.
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
if let dateContent = jsonResult["11/08/22"] as? [[String:String]] {
for group in dateContent {
people.appendContentsOf(group.keys)
group.values.forEach { companies.insert($0) }
}
}
}
} catch let error as NSError {
print(error)
}
})
jsonQuery.resume()
print(people)
print(companies)
Result:
["Steve Balmer", "Bill Gates"]
["Microsoft"]
let keys=jsonResult["11/08/22"]?.allKeys as? [String];
let values=jsonResult["11/08/22"]?.allValues as? [String];
It was as simple as this
I am saving a parse query to a array but i ket the following error on if let objects = objects as? [PFObject]
And the following error happens Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals.
any one know how to solve this?
func getArray(funcstring: String){
var userGeoPoint: PFGeoPoint
PFGeoPoint.geoPointForCurrentLocationInBackground {
(geoPoint: PFGeoPoint?, error: NSError?) -> Void in
if error == nil {
userGeoPoint = geoPoint!
}
}
var searchQuery: [String] = [String]()
var query = PFQuery(className:"User")
query.whereKey("geoLocation", nearGeoPoint:userGeoPoint)
query.limit = 100
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
} else {
print("\(error?.userInfo)")
}
}
}
objects is declared as [PFObject]?.
You're going to downcast the object to something the compiler already knows.
Just check for nil
if let unwrappedObjects = objects {
for object in unwrappedObjects {
self.searchQuery.append(object.objectForKey("objectId") as! String)
}
}
or still "swiftier"
if let unwrappedObjects = objects {
self.searchQuery = unwrappedObjects.map{ $0["objectId"] as! String }
}
I'm using the Realm to save some objects and the user has the ability to reload them through a network function.
class Task: Object {
dynamic var id: String = ""
dynamic var price: Double = 0
override class func primaryKey() -> String {
return "id"
}
func fillNew(json: JSON) {
self.id = json["id"].stringValue
self.name = json["prive"].doubleValue
}
}
The network function get an array of json to build these objects. Once these new objects are created, I pass them through an add or update but when I fetch them again the fields have not changed.
func getPendingTasks(completion: (JSON?, NSError?) -> ()) {
let urlString = ".."
Alamofire.request(.GET, urlString).responseJSON { response in
let json = response.result.value != nil ? JSON(response.result.value!) : nil
dispatch_async(dispatch_get_main_queue()) {
completion(json, response.result.error)
}
}
}
func getTasks() {
self.getPendingTasks() { json, error in
if let error = error {
return
}
let jsonTasks = json!["tasks"].arrayValue
for jsonTask in jsonTasks {
let task = Task()
task.fillNew(jsonTask)
self.tasks.append(task);
}
self.tasks = Task.sortGenericTasks(self.tasks)
dispatch_async(dispatch_get_main_queue()) {
let realm = try! Realm()
try! realm.write {
realm.add(self.tasks, update: true)
}
}
}
}
I'm currently using the latest version of realm, but can not pinpoint exactly what is happening or if I'm doing something wrong.
Several days I'm trying to crack why my code doesn't work and everything I've tried doesn't give me any result. Heres the deal:
There is a Booking class that contains userFrom who made booking
let query = PFQuery(className: "Booking")
query.whereKey("offer", equalTo: offer.pfObject!)
if self.typeOfUser == .COOK { //! If user is a Cook
query.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
if let objects = objects {
self.bookings = objects
self.usersIds = [String]()
for object in objects {
let userFrom = object.objectForKey("userFrom") as? PFObject
let userId = userFrom!.objectId! as String
self.usersIds.append(userId)
}
self.getUserInfoForBooking()
} else {
print("Something went wrong")
}
}
})
}
From every user I get objectId and append it to the [String] array. Then I query users with their IDs
private func getUserInfoForBooking() {
let userQuery = PFQuery(className: "User")
userQuery.whereKey("objectId", containedIn: self.usersIds)
userQuery.findObjectsInBackgroundWithBlock({ (objects : [PFObject]?, error : NSError?) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
print(objects!)
if let objects = objects {
for object in objects {
self.users.append(object)
}
self.collectionView.reloadData()
}
}
})
}
In this query I always get an empty array.
Whatever I did, whatever I've changed always [] in response :(
This is the wrong way to query users
let userQuery = PFQuery(className: "User")
Because the class name is private. You should be creating the query as
let userQuery = PFUser.query()
I am retrieving data in data. This is my code..
var data:NSMutableArray = NSMutableArray()
func loadData() {
data.removeAllObjects()
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSArray = self.data.reverseObjectEnumerator().allObjects
self.data = array as! NSMutableArray // Getting error here.. Could not cast value of type '__NSArrayI' (0x10391c420) to 'NSMutableArray' (0x10391c4e8).
self.tableView.reloadData()
}
}
}
please somebody help me.. i m stuck here and i am beginner .
Do casting in proper way like as follows :
var findData:PFQuery = PFQuery(className: "Sweets")
findData.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error != nil {
println(error)
} else if let objects = objects {
for object in objects {
self.data.addObject(object)
}
var array:NSMutableArray = NSMutableArray(array: self.data.reverseObjectEnumerator().allObjects)
self.data = array as NSMutableArray
self.tableView.reloadData()
}
}