how to parse json with alamofire and swiftjson? - xcode

I'm using swiftjson and alamofire to parse the json.pls help fix my code.
here the json array
Below are my code
RestClient.sharedClient.getUserWallet(uid: uid!, token: token!) { (json, error) in
print(json as Any)
self.tableRows = json!["data"].count
//ALL BELOW IS DONE BY SWIFTYJSON
let jsonArray = json?["data"].array
if jsonArray != nil {
for object in jsonArray! {
let walletCells: UserWalletCells = UserWalletCells(json: object)
self.userWalletCells.append(walletCells)
}
}
class PackageList {
var id: Int?
var user_id: String?
var amount: Int?
var currency_id: Int?
var release_rate: Double?
var release_per_day: Int?
var release_date: String?
var end_date: String?
var total_release: Int?
var tier_id: Int?
var is_active: Int?
var created: String?
var modified: String?
var remainingdays: Int?
init(json: JSON){
self.id = json["id"].intValue
self.user_id = json["user_id"].stringValue
self.amount = json["amount"].intValue
self.currency_id = json["currency_id"].intValue
self.release_rate = json["release_rate"].doubleValue
self.release_per_day = json["release_per_day"].intValue
self.release_date = json["release_date"].stringValue
self.end_date = json["end_date"].stringValue
self.total_release = json["total_release"].intValue
self.tier_id = json["tier_id"].intValue
self.is_active = json["is_active"].intValue
self.created = json["created"].stringValue
self.modified = json["modified"].stringValue
self.remainingdays = json["remainingdays"].intValue
}
}
I'm using swiftjson and alamofire to parse the json.pls help fix my code.

Please try this it will help you
let json = JSON(response)
let dictResult = json["data"].dictionaryValue
let arrayValue = dictResult["apckage"].arrayValue
var arrList = [PackageList]()
for i in 0..<arrayValue.count{
let packageList = PackageList()
let dictRespose = arrayValue[i]
packageList. id = dictRespose["id"].stringValue
packageList. user_id = dictRespose["user_id"].stringValue
packageList. amount = dictRespose["amount"].stringValue
arrList.append(packageList)
}
return arrTaxLis
Like this you put all your key. It may helps you. Thank you.

Related

Casting NSManagedObject property from num to Bool in swift

I know that question has been asked many times, but the solutions didn't work with me. I have the following NSManaged object class:
#NSManaged var cellColor: AnyObject
#NSManaged var des: String
#NSManaged var name: String
#NSManaged var switcher: NSNumber
And when trying to assign this value to a var as a bool when loading the managed object, I get an error. This is an example of assigning the value to a var:
func loadData(){
var appDel = UIApplication.sharedApplication().delegate as AppDelegate
var context = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Row")
var result:NSArray = context.executeFetchRequest(request, error: nil)!
if result.count > 0 {
for i in result{
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher:Bool{
get{
return i.switcher == NSNumber(bool: true)
//the problem happens here
However, when I try a simple example of casting in this way, It works well.
How to solve that ??
I think it just like this:
for i in results {
var name = i.name as String
var des = i.des as String
var color = i.cellColor as UIColor
var switcher: Bool {
return Bool(i.switcher)
}
}
Didn't test that though.

Realm is returning an empty object when I convert it to an array

Using Realm in a Swift application. I'm fetching users from Realm and want to return an array of users (as my app also uses Parse, it's easier if they are all arrays I'm guessing).
Here is my code:
class func fetchUsersFromDB() -> [User]{
var users = [User]()
let realm = Realm()
var allUsers = realm.objects(User)
users = Array(allUsers)
return users
}
When I do a dump of allUsers I can see a Realm result. But when I dump users it shows me the object with default values.
Any ideas what I'm doing wrong?
Here is how I declare the User model
class User: Object {
dynamic var objectId: String = ""
dynamic var username: String = ""
dynamic var password: String = ""
dynamic var emailVerified: Bool = false
dynamic var email: String = ""
dynamic var firstName: String = ""
dynamic var defaultRelationshipId: String = ""
dynamic var picture: NSData = NSData()
dynamic var updatedAt: NSDate = NSDate()
dynamic var createdAd: NSDate = NSDate()
override static func primaryKey() -> String? {
return "objectId"
}
}

How to wait for a background function to finish before calling another one in swift?

I will try to explain briefly what the situation is.
I am building a quiz app and I wanted it to work mainly using the internet, but also to work for a while when the user is disconnected. The older code I was using was made only with synchronous queries, it was taking more time than what I expected. So i decided to reformulate it.
The situation I projected is the following:
When my user selects a subject the app will synchronously get 1 question for each subsubject in order to be ready for my user click and to be faster.
After getting this first question, the app would then get another 4 (or how much is needed to complete 5) for each of the subsubjects asynchronously, while the user is occupied answering the first question that was presented to him.
Finally, the app would save the objects in the local datastore, so that the user can answer 5 questions for each subsubject when he is not connected.
Here is my code:
func getQuestionsRemotelyandSave (subsubject:String?, subject:String?, arrayOfSubsubjects:[String]?) {
self.getFromUserDefaults()
if Reachability.isConnectedToNetwork() == true {
if self.needsToGetQuestions == true {
let user = PFUser.currentUser()
var query = PFQuery(className: "Questions")
query.whereKey("answeredBy", equalTo: user)
query.whereKey("grade", equalTo: user["grade"])
if subsubject != nil && subject == nil {
query.whereKey("subsubject", equalTo: subsubject)
query.limit = 2
let array = query.findObjects()
for item in array {
let object = item as PFObject
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pin()
}
query.limit = 3
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]!, error:NSError!) -> Void in
if error == nil {
let questions = objects as [PFObject]
var QuestionsToPin = [PFObject]()
for object in questions {
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pinInBackground()
}
}
})
}
if subsubject == nil && subject != nil {
var firstTime = true
var semaphore = dispatch_semaphore_create(0)
query.limit = 1
for item in arrayOfSubsubjects! {
if item != "Todas as matérias" {
var query3 = PFQuery(className: "Questions")
query3.fromLocalDatastore()
query3.whereKey("subsubject", equalTo: item)
let count = query3.countObjects()
if count == 0 {
query.whereKey("subsubject", equalTo: item)
let array:NSArray = query.findObjects()
for item in array {
let object = item as PFObject
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pin()
}
}
if count > 0 {
var limit = 5 - count
if limit < 0 {
limit = 0
}
query.limit = limit
if firstTime == false {
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
query.findObjectsInBackgroundWithBlock({ (objects:[AnyObject]!, error:NSError?) -> Void in
if error == nil {
let questions = objects as [PFObject]
for object in questions {
var QuestionToPin = PFObject(className: "Questions")
QuestionToPin["Question"] = object["Question"] as String
QuestionToPin["rightAnswer"] = object ["rightAnswer"] as String
QuestionToPin["wrongAnswer1"] = object ["wrongAnswer1"] as String
QuestionToPin["wrongAnswer2"] = object ["wrongAnswer2"] as String
QuestionToPin["wrongAnswer3"] = object ["wrongAnswer3"] as String
QuestionToPin["grade"] = object["grade"] as String
QuestionToPin["subject"] = object ["subject"] as String
QuestionToPin["subsubject"] = object ["subsubject"] as String
QuestionToPin["feedback"] = object ["feedback"] as? String
QuestionToPin["shortFeedback1"] = object ["shortFeedback1"] as? String
QuestionToPin["shortFeedback2"] = object ["shortFeedback2"] as? String
QuestionToPin["shortFeedback3"] = object ["shortFeedback3"] as? String
QuestionToPin.pinInBackground()
}
dispatch_semaphore_signal(semaphore)
firstTime = false
}
})
}
}
}
}
}
}
}
The problem I'm facing is that I cant request multiple asynchronous functions from Parse. What I thought was maybe waiting for an asynchronous function to finish before the other one starts, but I wanted it to happen without the user having to wait. Is there a way of doing it?
Thank you.

Signal SIGABRT in Swift using NSuserdefaults

I'm building a swift game and a need to set up a class. My code works for all the elements in my class, but not for this.
func saveInformationMember(){
var MembersDefaultName = NSUserDefaults.standardUserDefaults()
MembersDefaultName.setValue(globalCurrentMembers, forKey: "globalCurrentMembersData")
MembersDefaultName.synchronize()
}
GlobalCurrentMembers is an array of Member which looks like that:
class Member {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func Init(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
To save your class this way, Member needs to conform to the NSCoding protocol.
Thx to Aaron Brager for is response. This is the response :
func saveInformationMember(){
let data = NSKeyedArchiver.archivedDataWithRootObject(globalCurrentMembers)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "member")}
func loadInformationMember(){
if let data = NSUserDefaults.standardUserDefaults().objectForKey("member") as? NSData {
globalCurrentMembers = NSKeyedUnarchiver.unarchiveObjectWithData(data) as [Member]
}
And my class:
class Member : NSObject, NSCoding {
var image = String ()
var name = String ()
var progression = Int()
var round = Int()
var level = Int()
var imageProgression = [UIButton]()
func initiation(){
image = "default.png"
name = "default"
progression = 0
round = 0
level = 0
}
required convenience init(coder decoder: NSCoder) {
self.init()
self.image = decoder.decodeObjectForKey("image") as String!
self.name = decoder.decodeObjectForKey("name") as String!
self.progression = decoder.decodeIntegerForKey("progression") as Int!
self.round = decoder.decodeIntegerForKey("round") as Int!
self.level = decoder.decodeIntegerForKey("level") as Int!
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.image, forKey: "image")
coder.encodeObject(self.name, forKey: "name")
coder.encodeInt(Int32(self.progression), forKey: "progression")
coder.encodeInt(Int32(self.round), forKey: "round")
coder.encodeInt(Int32(self.level), forKey: "level")
}}

here is the code to fetch username and password from the xml file but it does't fetch the the data?

Here is the code to fetch username and password from the xml file but it does't fetch the the data?
private var myXML: XML = new XML();
private function connect(event: Event): void {
var str1: String = username.text.toString();
trace(str1);
var str2: String = password.text.toString();
trace(str2);
var str3: String = myXML.authentication.username;
Alert.show(str3);
var str4: String = myXML.authentication.password;
if (str1 == str3 && str2 == str4) {
Alert.show("sucessfully Connected")
} else {
Alert.show("invalid username password");
}
}
Where you are assigning data for myXML and what is your xml?
var settingFile:File;
var stream:FileStream;
var resultXML:XML;
settingFile = settingFile.resolvePath("setting.xml");
stream = new FileStream;
if(settingFile.exists)
{
stream.open(settingFile,FileMode.READ);
resultXML = XML(stream.readUTFBytes(stream.bytesAvailable));
stream.close();
var xmlDoc:XMLDocument = new XMLDocument(resultXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
}
from that resultObj u can access the username and password
if you are using FlexApplication then convert the xml file to xmlDocument and decode it. then from the decoded object you can get the username and password.
var xmlDoc:XMLDocument = new XMLDocument(myXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
you can try like this.
private var myXML: XML = new XML();
private function connect(event: Event): void {
var xmlDoc:XMLDocument = new XMLDocument(myXML.toString());
var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);
var str1: String = username.text.toString();
trace(str1);
var str2: String = password.text.toString();
trace(str2);
var str3: String = resultObj.authentication.username;
Alert.show(str3);
var str4: String = resultObj.authentication.password;
if (str1 == str3 && str2 == str4) {
Alert.show("sucessfully Connected")
} else {
Alert.show("invalid username password");
}
}
Why don't you try to load the XML file suing the URL loader and capture the COMPLETE event to fetch the data?

Resources