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!
Related
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.
I am having an error appear in Xcode saying Downcast from '[PFObject]?' to '[PFObject]' only unwraps optionals; did you mean to use "!"?
var iDArray = [String]()
var nameArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ObjectIDQuery = PFQuery(className: "Songs")
ObjectIDQuery.findObjectsInBackgroundWithBlock({
(objectsArray: [PFObject]?, error: NSError?) -> Void in
var objectIDs = objectsArray as! [PFObject]
for i in 0...objectIDs.count{
self.iDArray.append(objectIDs[i].valueForKey("objectID") as! String)
NSLog("\(objectIDs)")
Xcode file image
It is better to use guard in this situation. Code below will safely unwrap optional objectsArray and, in case optional is nil, it will not execute further code. Also you can write this part of code a little more beautiful :)
ObjectIDQuery.findObjectsInBackgroundWithBlock() { (objectsArray: [PFObject]?, error: NSError?) -> Void in
guard let objectIDs = objectsArray else { return }
self.iDArray += objectIDs.map { $0.valueForKey("objectID") as! String }
}
You probably did mean to use "!". Change this line:
var objectIDs = objectsArray as! [PFObject]
to this:
var objectIDs = objectsArray!
Since you are just unwrapping the array, there is no need to cast it.
This message means that a downcast is not needed because the compiler knows the type [PFObject]? – as you can see in the block signature.
The recommended way is first to handle the error. If it's nil you can safely unwrap the optional
ObjectIDQuery.findObjectsInBackgroundWithBlock({
(objectsArray: [PFObject]?, error: NSError?) -> Void in
if error != nil {
// handle the error
} else {
for anObject in objectsArray! {
self.iDArray.append(anObject["objectID"] as! String)
}
}
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]
var titles = [String]()
var descriptions = [String]()
func retrieveData () {
var query = PFQuery(className: "Main")
// get the actual data
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
println("Error retrieving data")
} else {
self.titles.append(object["Labels"] as! String) // ERROR!
self.descriptions.append(object["desc1"] as! String) // ERROR!
}
}
}
I have 2 arrays and I want to retrieve data from Parse and add it to those arrays, but I get this error:
Cannot invoke 'append' with an argument list of type '(String)'
What am I doing wrong ?
Edit: this is what I get when I println(object) :
Optional(<Main: 0x7fc24b84e410, objectId: jy7LrEOMk0, localId: (null)> {
Labels = labels;
desc1 = desc1;
desc2 = desc2;
desc3 = desc3;
desc4 = desc4;
desc5 = desc5;
})
Message from debugger: got unexpected response to k packet: OK
After spending several hours trying & searching, this is the correct answer:
self.titles.append(object?.objectForKey("Labels") as! String)
self.descriptions.append(object?.objectForKey("desc1") as! String)
The answer is so simple, but somehow the Parse.com docs don't have a single sample of it. Anyway I hope that helps anyone else who may get stuck at the same problem.
I'm struggling to loop through an array of dictionary values returned from a web service call.
I've implemented the following code and I seem to be encountering a crash on running.
I'd also like to store the results into a custom Struct. Really having difficulty achieving this and the answers on here so far haven't worked. Would be grateful if someone is able to help.
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
if let list = nudgesJSONResult["nudges"] as? [[String:String]] {
for nudgeDict in list {
let location = nudgeDict["location"]
println(location)
}
}
}
})
task.resume()
}
NOTICE
This answer was written using Swift 1.2 and as such, there may be some slight stylistic and syntax changes required for the answer to work depending on your current Swift system.
Answer -- Swift 1.2
This line is crashing your code:
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
You're forcing a cast that Swift can't handle. You never make it to your for-loop.
Try changing your code to look more like this:
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String : AnyObject]
if let nudges = nudgesJSONResult["nudges"] as? [[String : String]] {
for nudge in nudges {
let location = nudge["location"]
println("Got location: \(location)")
println("Got full nudge: \(nudge)")
}
}
}
})
task.resume()
Thanks,
I created the following Struct which stored the data, and also lets me create dictionaries in the view controller for a particular index.
struct NudgesLibrary {
var location: NSArray?
var message: NSArray?
var priority: NSArray?
var date: NSArray?
var nudges: NSArray?
init(nudgesObject: AnyObject) {
nudges = (nudgesObject["nudges"] as NSArray)
if let nudges = nudgesObject["nudges"] as? NSArray {
location = (nudges.valueForKey("location") as NSArray)
message = (nudges.valueForKey("message") as NSArray)
priority = (nudges.valueForKey("priority") as NSArray)
date = (nudges.valueForKey("date") as NSArray)
}
}
}