Error while retrieving Parse data into an array - arrays

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.

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.

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.

Swift: Looping through a Dictionary Array

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)
}
}
}

Add variables to array declared before if else in swift

Im trying hard to learn ios development and have followed a guide to build a simple quiz app. I'm trying to connect the app to database by parsing from json.
Everything is working fine regarding that part. I now want to add the variables created from json into an array.
I have declared the array before let task:
var spormslaArray = []
I want to add questions to the array inside the task, something like this:
var question[] = [id, questionItself, answer1, answer2, answer3, answer4, correctAnswerJson]
spormslaArray.append(question)
I'm getting these errors..
App/ViewController.swift:127:41: Consecutive statements on a line must be separated by ';'
App/ViewController.swift:129:29: Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit
The task:
The task:
let task = session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
else {
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
else {
let questions=jsonResult["data"] as? [[String:String]]
if (questions != nil) {
for question in questions! {
questionNummer += 1
let answer1=question["answerOne"]!
let answer2=question["answerTwo"]!
let answer3=question["answerThree"]!
let answer4=question["answerFour"]!
let id=question["id"]!
let questionItself=question["questionTemplate"]!
let correctAnswerJson=question["correctAnswer"]!
println(id, questionItself, answer1, answer2, answer3, answer4, correctAnswerJson)
var question[] = [id, questionItself, answer1, answer2, answer3, answer4, correctAnswerJson]
spormslaArray.append(question)
}
}
}
}
})
task.resume()
Questions are hardcoded this way :
let questionSeven = questionTemplate("lol", answerOne: "av ormer (worms)", answerTwo: "virus infeksjon", answerThree: "installeres av en Trojaner eller en 'datasnik'", answerFour: "Bot aktivitet", correctAnswer: 3)
Then added to the array
spormslaArray = [questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix,questionSeven]
Then sent to a function to set up questions:
func questionTemplate(question:String, answerOne:String, answerTwo:String, answerThree:String, answerFour:String, correctAnswer:Int) -> NSArray {
//Set the question
var quizQuestion = question
//set the answers and the right answer
var firstAnswer = answerOne
var secondAnswer = answerTwo
var thirdAnswer = answerThree
var fourthAnswer = answerFour
var rightAnswer = correctAnswer
var gjennverendeSporsmal = 1
//Add all the questions and answers to an array
let questionAnswerArray = [question, firstAnswer, secondAnswer, thirdAnswer, fourthAnswer, rightAnswer]
return questionAnswerArray
}
I'm sure there is a easy noob-thing I'm missing. Do any of you see my mistake?
You need to declare it as
var spormslaArray = [AnyObject]()
The trailing brackets indicate that you want to instantiate it. Just using [] will make it of type NSArray which is non-mutating. Instead of AnyObject you should use the actual type you want to put in. In your case it's some array again. You can do that by declaring that type like
typealias MySpecialArray = [AnyObject] // or whatever is inside, maybe String
and then use that
var spormslaArray = [MySepcialArray]()
You get the idea once you use it.

Swift array doesn't hold values

I ran into the following problem while trying to build something with Swift. Apparently, the values that I added into an array are not saved pass some point. They are sent just fine with the protocol while the task is running, but after it completes, if I try to see the values in the array, it returns empty.
What am i doing wrong? My guess is that it get deallocated after task finishes. If that is so, is there a way to make it strong? Is there something I should know about this task thingie? Can you please explain to me how this works and what I should do?
Here is the code:
var exchangeArray : ExchangeValues[] = [];
func fetchResult(){
var currenciesOrder = ["EUR", "USD", "GBP", "CHF", "NOK", "SEK", "DKK", "CZK","TRY", "BGN", "MDL", "PLN", "XDR", "XAU", "UAH", "RUB", "RSD","CAD", "AUD", "JPY", "EGP", "BRL","HUF", "MXN","KRW", "CNY","NZD","INR","AED", "ZAR"];
let dateFormat = NSDateFormatter();
dateFormat.dateFormat = "yyyy-MM-dd";
for days in 0..2 {
let daysToSubstract = Double(60*60*24*days);
let date : String = dateFormat.stringFromDate(NSDate().dateByAddingTimeInterval(-daysToSubstract));
var url: NSURL = NSURL(string: "http://openapi.ro/api/exchange/all.json?date=" + date);
var session = NSURLSession.sharedSession();
var task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) -> Void in
if (response != nil){
var err: NSError?;
if(err?) {
println("request Error \(err!.localizedDescription)");
}
//send the result to protocol
let results = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary;
let temp : NSDictionary = results["rate"] as NSDictionary;
for key in 0..currenciesOrder.count{
for (currencyKey : AnyObject, currencyValue : AnyObject) in temp {
if currenciesOrder[key] as String == currencyKey as String {
let tempExchange = ExchangeValues(currency: currencyKey as? String, value: currencyValue.doubleValue, date:date );
self.exchangeArray.append(tempExchange);
}
}
}
self.delegate?.didReceiveResults(self.exchangeArray);
} else {
println("error: \(error.localizedDescription)");
}
})
task.resume();
}
println("\(exchangeArray.count)");
}
I kind of figured out what the problem is:
The task block returns void, so I think it empties the array after it finishes. The result is to create another function that gets called from the task, where the array works just fine (it gets passed the values while they exist) and any further processing can be done there.
I hope this helps someone. The code is as easy as this:
func sendResults(array : ExchangeValues[]) -> Void{
println("\(exchangeArray.count)"); }
Of course, you can have the function return something if you need to.

Resources