I want to load array data from parse (swift) - arrays

I have to make a Comment, being an attempt to import the Array in the Parse. However, there is a problem.
When i try to load array from Parse, my output is ("Blah","Blah","Blah")
It's a tuple.... not a Array TT.....
How Can I bring in the Array from Parse Correctly?
it's my fetch function from parse
func fetchDataFromParse(){
var query = PFQuery(className:"Cafe")
query.whereKey("name", notEqualTo: "")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
self.imageText.append(object.objectForKey("name")! as! String)
self.commentArray = (object.objectForKey("comment")!) // This is array of comment from Parse!!
self.imageFiles.append(object.objectForKey("imageFile") as! PFFile)
self.messageTableView.reloadData()
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
}

You may need to use the following to cast this as a Swift Array:
self.commentArray = object.objectForKey("comment") as? [AnyObject]

Related

Swift. Error: Cannot convert value of type '[AnyObject?]' to expected argument type 'AnyObject?'

Trying to save data offline. But, getting the error of Cannot convert value of type '[AnyObject?]' to expected argument type 'AnyObject?'. Couldn't figure out how to convert AnyObject array to String array. Thank you for you guys help.
// outside the function
var senderArray = [String]()
var messageArray = [String?]()
var photoArray = [UIImage?]()
// func.........
query.whereKey("downloaded", equalTo: false)
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error != nil {
}
for object in objects! {
self.senderArray.append(object.objectForKey("sender") as! String)
self.messageArray.append(object.objectForKey("message") as? String)
if object.objectForKey("photo") != nil {
if let converyPFFile = object.objectForKey("photo") as? PFFile{
let temp = try! converyPFFile.getData()
let image = UIImage(data: temp)
self.photoArray.append(image)
}
} else {
self.photoArray.append(nil)
}
}
var tempLocalNameArray = [AnyObject?]()
var tempLocalMessageArray = [AnyObject?]()
var tempLocalImageArray = [AnyObject?]()
if NSUserDefaults.standardUserDefaults().arrayForKey("nameArray") != nil {
tempLocalNameArray = NSUserDefaults.standardUserDefaults().arrayForKey("nameArray")!
tempLocalMessageArray = NSUserDefaults.standardUserDefaults().arrayForKey("messageArray")!
tempLocalImageArray = NSUserDefaults.standardUserDefaults().arrayForKey("imageArray")!
}
for i in 0 ..< self.senderArray.count {
tempLocalNameArray.append(self.senderArray[i])
tempLocalMessageArray.append(self.messageArray[i])
tempLocalImageArray.append(self.photoArray[i])
}
// error highlighted
NSUserDefaults.standardUserDefaults().setObject(tempLocalNameArray, forKey: "nameArray")
// error highlighted
NSUserDefaults.standardUserDefaults().setObject(tempLocalMessageArray, forKey: "messageArray")
// error highlighted
NSUserDefaults.standardUserDefaults().setObject(tempLocalImageArray, forKey: "imageArray")
self.loadChat()
}
You are trying to store images with NSUserDefaults. But NSUserDefaults does not store any kind of data. Please read the documentation:
The value parameter can be only property list objects: NSData,
NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and
NSDictionary objects, their contents must be property list objects.
This article may help you.

Query many Date formats from parse into Array Swift

I am trying to retrieve Objects from parse and take the "createdAt" and append to an Array to put it in a tableview i got this so far:
(the lines with //// is the lines that not working)
var date = [String]()
override func viewDidLoad() {
messageTextfield.sizeToFit()
var query = PFQuery(className:"messages")
query.whereKey("receivers", equalTo:(user?.username)!)
query.findObjectsInBackgroundWithBlock {
(objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
print("Successfully retrieved \(objects!.count) messages.")
for object in objects! {
self.messagesSender.append(object["sender"] as! (String))
self.messagesID.append(object.objectId!)
self.messageMessage.append(object["message"] as! (String))
/////var messageCreated = object["createdAt"]
/////let dateFormatter = NSDateFormatter()
/////dateFormatter.dateFormat = "MMM,dd-YYYY-hh"
/////self.date.append(dateFormatter.stringFromDate(messageCreated as! NSDate))
print(self.messagesID)
print(self.messagesSender)
print(self.messageMessage)
self.reloadTableView()
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
the error occurs at line "/////self.date.append(dateFormatter.stringFromDate(messageCreated as! NSDate))" and it says "unexpectedly found nil while unwrapping an Optional value."
Ahh! I'v run into this before! createdAt is a build in method with Parse for swift. Replace var messageCreated = object["createdAt"] with var messageCreated = object.createdAt! and you'll be good to go!

How to remove object from array in Parse with Swift 2.0

I have an array of items in a column in Parse.
I am able to fetch that array with the code :
let query:PFQuery = PFQuery(className: "Names")
query.whereKey("date", greaterThan: NSDate())
query.findObjectsInBackgroundWithBlock {
(object, error) -> Void in
if object != nil
{
if(object!.count != 0)
{
for messageObject in object! {
self.arrayNames = ((messageObject as! PFObject)["arrayNames"] as? [String])!
}
} else {
print("No Objects")
}
}
} // self.arrayNames = ["Aruna", "Bala", "Chitra", "Divya"]
In this I want to delete an single item and again save it to the parse.
I can delete it locally as removeAtIndex but how can I remove that from Parse?
After you have retrieved your array, remove the one item you do not want, reassign the new array to the retrieved object and then save.
In the names, if I wanted to delete Aruna,
self.arrayNames.removeAtIndex(0)
Then to update this array in Parse,
let query:PFQuery = PFQuery(className: "Names")
query.whereKey("date", greaterThan: NSDate())
query.findObjectsInBackgroundWithBlock {
(object, error) -> Void in
if object != nil {
object!.setValue(self.arrayNames, forKey: "arrayNames")
object!.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if(success) {
print("Success")
} else {
print("Error")
}
}
}
}
I found that, i cant directly delete an single element from an array in a column in Parse. So I am updating that array with my local array. It works!
If you read the docs you will find one of the delete methods useful such as deleteInBackgroundWithBlock:
object.deleteInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in
// do whatever you need to do
}

Type 'String' does not conform to protocol 'NSCopying' - Array swift json Error

sorry in advance for my bad english.
I have a problem with my Swiftcode, i'm new in Swift so maybe you can help me :)
Here is my Code.
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil)
{
println("error\(error)")
return;
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json
{
var resultValue:String = parseJSON["message"] as String!;
println("result: \(resultValue)")
self.LabelFalscheEingabe.text = "\(resultValue)";
if(resultValue == "Success")
{
var Projects:Array = parseJSON["projects"] as Array!; // here is the Error
}
}
task.resume()
}
'projects' is a variable from type Array on the server, so i want to get it as Array from the server, but if I try this i get the following error.
Error: "Type 'String' does not conform to protocol 'NSCopying'".
Thanks in advance :)
YourProjects array can't be declared like that, Swift has to know the type of the objects in the array.
If you don't know the type, then make it an array of AnyObject:
if let Projects = parseJSON["projects"] as? [AnyObject] {
// do something with Projects
}
If you know it's an array of Strings, for example:
if let Projects = parseJSON["projects"] as? [String] {
// do something with Projects
}
An array of Integers:
if let Projects = parseJSON["projects"] as? [Int] {
// do something with Projects
}
An array of dictionaries made from JSON:
if let Projects = parseJSON["projects"] as? [[String:AnyObject]] {
// do something with Projects
}
Etc.

Xcode , Parse - Storing values from an array object in a local array

I want the user to upload an image, and other users leave replies to that image, everything works fine so fat except i can't get save the replies inside the "replies" object/column in Parse into my local array in order to display them. it can't accept the : for in method.
override func viewDidLoad() {
super.viewDidLoad()
var query = PFQuery(className:"Posts")
query.getObjectInBackgroundWithId(cellID) {
(objects: PFObject!, error: NSError!) -> Void in
if error == nil {
println(objects["replies"])
self.repliesArray.append(objects["replies"] as String) // <- problem Here
} else {
println("Error retreiving")
self.displayError("Error", error: "Error retrieving")
}
}
}
If the replies column is a string, try this:
if error == nil {
var array = objects.objectForKey("replies") as [String]
for obj in array {
self.repliesArray.append(obj as String)
}
}

Resources