Arithmetic operation fails on AnyObject - ios

I'm doing an app in iOS Swift with Parse. I need to increment 1 every time a product is viewed. Following is my code to do that:
var prodQuery = PFQuery(className: "prodDet")
let id = prodId[currprod] as String
prodQuery.whereKey("objectId", equalTo:id)
prodQuery.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects {
var key1: Int = object["key1Total"]! as Int
var key1New: Int = key1 + 1
object["key1Total"] = key1New
}
}
}
The above code gives error "#lvalue$T5 is not identical to AnyObject...". Is anything wrong the way I'm dealing with AnyObject object here; How do we do arithmatic calculation on Parse AnyObjects?
Could somebody please shed some light?

I sorted it out, seems like I should cast the object as PFObject and use object.setValue. The following is the working code:
var prodQuery = PFQuery(className: "prodDet")
let id = prodId[currprod] as String
prodQuery.whereKey("objectId", equalTo:id)
prodQuery.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
for object in objects as [PFObject] {
var keyVal = object["key1Total"]! as Int
var keyNew = keyVal + 1
object.setValue(keyNew, forKey: "key1Total")
object.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
//
} else {
//
}
}
}
}
}
object.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
//
} else {
//
}
}
}
}
}

Related

Is it possible to query dictionary on parse.com?

i’m trying to search dictionary match result but no luck
my parse dictionary column look like this
columnName: Tag property: object
{"firstKey”:”David”,”secondKey”:”Guetta”}
columnName: name property: string
cool

when I try to search name column
here is my code snippet,
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("name", equalTo: "cool")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get result below
objects is Optional([ {
Tag = {
firstKey = David;
secondKey = Guetta;
};
name = cool;
tagArray = (
David,
Guetta
);
}])
i've try array column
columnName: tagArray property: array
["David","Guetta"]
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("tagArray", equalTo:"David")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get result
objects is Optional([ {
Tag = {
firstKey = David;
secondKey = Guetta;
};
name = cool;
tagArray = (
David,
Guetta
);
}])
but when i try to search dictionary column
columnName: Tag property: object
{"firstKey”:”David”,”secondKey”:”Guetta”}
like this
static func parseQueryDictionary() {
let query = PFQuery(className:"TestDictionary")
query.whereKey("Tag", equalTo:"David")
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil && objects != nil {
print("objects is", objects)
} else {
print(error)
}
}
}
i get no result
objects is Optional([])

i’ve try google and parse official doc but can’t find this case, is it possible to do that?
i've try search string column, array column it's work but only dictionary column not work...
search in google with "findObjectsInBackgroundWithBlock" in swift.It will give you many results.
var query = PFQuery(className: parseClassName)
query.whereKey("Position", equalTo: "iOS Developer")//Here Position is column name and Sales Manager is value.
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
for object in objects {
}
}
else{
println("Error in retrieving \(error)")
}
})

Swift& Parse.com Adding values from a table into an array error not having a member named subscript

I have a table called Assesment
it has the name and send values of each task
what I needed to do is to retrieve all these tasks and store them in an array
and here is my code which gives me an error saying that PFObject doesn't have a member called send:
override func viewDidLoad() {
super.viewDidLoad()
//test
var taskQuery = PFQuery(className: "Assesment")
//run query
taskQuery.findObjectsInBackgroundWithBlock({
(success:[AnyObject]?, error: NSError?) -> Void in
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
ERROR>>>> taskMgr.addtask(object.name,send: object.name)
}
println(taskMgr)
}})
//test
// Do any additional setup after loading the view, typically from a nib.
}
even thought I tried to say instead
taskMgr.addtask(object)
AssesmentManager.swift class:
import UIKit
var taskMgr : AssesmentsManager = AssesmentsManager()
struct task {
var name = "Un-Named"
var send = false
}
class AssesmentsManager: NSObject {
var tasks = [task]()
func addtask(name: String, send: Bool) {
tasks.append(task(name: name, send: send))
}
}
UPDATE
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
if object["send"]=="true"{
taskMgr.addtask(object["name"], true )
}
else{
taskMgr.addtask(object["name"], false )}
}
I updated it to remove the string, boolean problem but I still have the same error of not having a member named subscript
UPDATE#2
This is what it looks like now, but still giving me an error that objects is unresolved:
var taskQuery = PFQuery(className: "Assesment")
//run query
taskQuery.findObjectsInBackgroundWithBlock({
(success:[AnyObject]?, error: NSError?) -> Void in
if (success != nil) {
for object:PFObject! in success as! [PFObject]{
for object in objects {
taskMgr.addtask(object["name"], (object["send"] == "true"))
}
}
println(taskMgr)
}})
In Swift 2.0, findObjects returns optional array of PFObject instead of optional AnyObject. Try this
override func viewDidLoad() {
super.viewDidLoad()
var taskQuery = PFQuery(className: "Assesment")
taskQuery.findObjectsInBackgroundWithBlock {
(success:[PFObject]?, error: NSError?) -> Void in
if let objects = success {
for object in objects {
taskMgr.addtask(object["name"], (object["send"] == "true"))
//taskMgr.addtask(object["name"], (object["send"].isEqual("true")))
}
}
}
}

Check if PFObject is nil

I want to check if a PFObject is nil
I retrieve the object
var userLibrary: PFObject?
func getUserLibrary(user: PFUser) {
self.libraryQuery = PFQuery(className: "Library")
self.libraryQuery?.whereKey("owner", equalTo: user)
self.libraryQuery?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
if objects!.count > 0 {
self.userLibrary = objects![0]
} else {
print(self.userLibrary)
}
}
})
}
The last line with the print statement prints out nil.
However when I check :
if userLibrary != nil {
}
Xcode tells me
Binary operator '!=' cannot be applied to operands of type 'PFObject' and 'NilLiteralConvertible'
How do I fix this ?
I'm not 100% sure that this will work, but did you try.
if let lib = userLibrary {
//do whatever
}
Let me know.
Also, if you are just using the first object of your query. It would better to use getFirstObjectInBackground

Parse save pointer

This is my code that tries to save the table/Class inscricoes
view.showHUD(view)
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = self.eventObj.objectId
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else { errorAlert.show(); self.view.hideHUD() }
}
This is my class / table where sorteioId is a pointer to my table/class sorteios
when I try to save an error of warning that can not save as a string pointer.
[Error]: invalid type for key sorteioId, expected Sorteios, but got string (Code: 111, Version: 1.7.5)
How do I send a pointer to table / class using parse?
You first need an instance of PFObject of type Sorteios. Revise your code like so:
view.showHUD(view)
var query = PFQuery(className: "Sorteios")
query.getObjectInBackgroundWithId(self.eventObj.objectId) {
(object: PFObject?, error: NSError?) -> Void in
if error == nil && object != nil {
// after finding Sorteios, you can assign it to inscricaoClass
var inscricaoClass = PFObject(className: INSCRICAO_CLASS_NAME)
inscricaoClass[INSCRICAO_SORTEIO_ID] = object
inscricaoClass.saveInBackgroundWithBlock { (success, error) -> Void in
if error == nil {
self.view.hideHUD()
} else {
errorAlert.show(); self.view.hideHUD() }
}
}
}

iOS Multiple save of parse objects with progress bar

I found this very interesting approach (Parse : is it possible to follow progress of PFObject upload) and I tried to convert the objective-c category in a swift extension. But I am overstrained with the values types unsigned long.
Please have a look in the following code - it throws the exception (line: let progress:Int32 = Int32(100*count/numberOfCyclesRequired)): fatal error: floating point value can not be converted to Int32 because it is either infinite or NaN.
I am also not sure how to handle the __block prefix in swift that the count changes will also occur out of the block.
extension PFObject {
class func saveAllInBackground(objects: [AnyObject]!, chunkSize:Int, block: PFBooleanResultBlock!, progressBlock:PFProgressBlock) {
let numberOfCyclesRequired:Double = Double(objects.count / chunkSize)
var count:Double = 0
PFObject.saveAllInBackground(objects, chunkSize: chunkSize, block: block) { (trig:Bool) -> Void in
count++
let progress:Int32 = Int32(100*count/numberOfCyclesRequired)
progressBlock(progress)
}
}
class func saveAllInBackground(objects: [AnyObject]!, chunkSize:Int, block: PFBooleanResultBlock!, trigger:(Bool) -> Void) {
let range = NSMakeRange(0, objects.count <= chunkSize ? objects.count:chunkSize)
var saveArray:NSArray = (objects as NSArray).subarrayWithRange(range)
var nextArray:NSArray = []
if range.length < objects.count {
nextArray = (objects as NSArray).subarrayWithRange(NSMakeRange(range.length, objects.count-range.length))
}
PFObject.saveAllInBackground(saveArray) { (succeeded:Bool, error: NSError!) -> Void in
if (error == nil && succeeded && nextArray.count != 0) {
trigger(true)
PFObject.saveAllInBackground(nextArray, chunkSize: chunkSize, block: block, trigger: trigger)
} else {
trigger(true)
block(succeeded,error)
}
}
}
}
Thanks for your help in advance.

Resources