My problem is adding new numbers to the array field in users. all the code seems to work but i have the problem with saveAll function. All the names are correct, as i've checked on several different occasions.
func taskAllocation(){
var query = PFUser.query()
var objectQuery:[PFUser] = [PFUser]()
query.whereKey("Year", equalTo: yearTextField.text.toInt())
query.whereKey("Class", equalTo: classTextField.text.toInt())
query.whereKey("Keystage", equalTo: keystageTextField.text.toInt())
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error != nil {
println(error)
} else {
if objects.isEmpty {
println("empty query")
}
else {
for object in objects as [PFUser] {
var test:[Int] = object["taskIDs"] as [Int]
test.append(self.getIndex)
println(test)
object["taskIDs"] = test
object["tasksCompleted"] = "hello"
objectQuery.append(object)
}//For
println(objectQuery.count)
if objectQuery.count != 0{
println("Success!!!")
println(objectQuery)
PFUser.saveAllInBackground(objectQuery)
}
}
}
}
This below is stored in the println(objectQuery) as you can see the taskIDs have been appended and the tasksCompleted contains the string. Which leads me to believe that there is a problem with the saveallinbackground function.
[<PFUser: 0x155f6510, objectId: W6TrPQwCQ7, localId: (null)> {
Class = 2;
Forename = "Joe ";
Keystage = 2;
Surname = Freeston;
Year = 4;
admin = false;
completedTaskIDs = (
);
taskIDs = (
0,
2,
4,
5,
6,
46
);
tasksCompleted = hello;
tasksCorrect = 0;
userType = Student;
username = jfreeston;
}, <PFUser: 0x1569b7a0, objectId: slLd1KBIaM, localId: (null)> {
Class = 2;
Forename = "Camilla ";
Keystage = 2;
Surname = Linhart;
Year = 4;
admin = false;
completedTaskIDs = (
);
taskIDs = (
0,
46
);
tasksCompleted = hello;
tasksCorrect = 0;
userType = Student;
username = clinhart;
}]
Not sure if anyone has more knowledge of the parse api, mainly how the saveall/saveallinbackground functions work maybe.
To save all in background as a user I would first create a PFUser variable, like
var NewUser = PFUser.currentUser
Then to save in background
newUser.saveInBackgroundWithBlock {
(success:Bool, error: NSError!) -> Void in {
}
Then you can put if-statements and stuff within those brackets to do what you need it to when successful. like:
if(success) {
performSegueWithIdentifier("YourSegue", sender: nil)
}
Related
I really need help with refactoring or breaking up code to smaller pieces. My Xcode can't even build project because it's too complicated.
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
I can't break up into smaller pieces because I have to assign results of UITextField to that function to push it to BackEnd. Code is too messy.
/* That's where I'm assigning values to Bools and selections */
#objc func handleSaveMZHD()
var NalichieTehPasportBol: Bool = false
if NalichieTehPasportResponse.text == "Да"{
NalichieTehPasportBol = true
} else if NalichieTehPasportResponse.text == "Нет"{
NalichieTehPasportBol = false
}
var NalichieElektroLambiBol: Bool = false
if (ElektroLampiResponse.text == "Да"){
NalichieElektroLambiBol = true
} else if ElektroLampiResponse.text == "Нет"{
NalichieElektroLambiBol = false
}
var NalichieLiftaBol: Bool = false
if NalichieLiftaResponse.text == "Да"{
NalichieElektroLambiBol = true
} else if NalichieLiftaResponse.text == "Нет"{
NalichieElektroLambiBol = false
}
var AktTehObsledSelection: Int = 0
if AktTehnObsledovaniyaResponse.text == "аварийный"{
AktTehObsledSelection = 1
} else if self.AktTehnObsledovaniyaResponse.text == "Не аварийный"{
AktTehObsledSelection = 2
}
var BalansPrinadlejnostiSel: Int = 0
if BalansPrinadlejResponse.text == "Государственная Собственность" {
BalansPrinadlejnostiSel = 1
} else if BalansPrinadlejResponse.text == "Частная Собственность" {
BalansPrinadlejnostiSel = 2
}
var OblicovkaSel: String = ""
if OblicovkaResponse.text == "Монолит"{
OblicovkaSel = "monolith"
}else if OblicovkaResponse.text == "Кирпич"{
OblicovkaSel = "brick"
}else if OblicovkaResponse.text == "Блоки"{
OblicovkaSel = "blocks"
}else if OblicovkaResponse.text == "Облицовка"{
OblicovkaSel = "facing"
}
/* That's function itself to push all that information to BackEnd */
updaTeRecord(o_model: "property.building", id: 207, attrs: [
"street": ulicaResponse.text,
"parking_area": PlowadParkingaResponse.text,
"builded_at": GodPostroikiResponse.text,
"all_size": Int(ObwayaPlowadDomaResponse.text!),
"land_size": Int(ObwayaPlowadUchastkaResponse.text!),
"apartment_amount": Int(KolvoKvartirResponse.text!),
"porch_amount": Int(KolvoPodezdovResponse.text!),
"level_amount": KolvoEtajeiResponse.text,
"is_tech_passport" : NalichieTehPasportBol,
"entrance_state": SostoyaniePodezdResponse.text,
"entrance_energy_saving_lamps": NalichieElektroLambiBol,
"entrance_windows_count": KolvoOkonResponse.text,
"entrance_windows_material": MaterialOkonResponse.text,
"lift_provided": NalichieLiftaBol,
"conclusion_of_technical_inspection": AktTehObsledSelection,
"lift_amount": Int(KolvoLiftovResponse.text!),
"lift_installed_at": DataUstanovkiLiftaResponse.text,
"lift_lifetime": SrokEkspluatLiftaResponse.text,
"lift_last_checked": DataPoslObslLiftaResponse.text,
"lift_company": ObslujOrganizaciyaResponse.text,
"lift_payment_method": TipOplatiLiftaResponse.text,
"power_consumption": PotreblyaemayaMownostResponse.text,
"registration_of_condominium": RegestraciyaKondominimumaResponse.text,
"date_of_condominium": DataRegestraciyaKondominimumaResponse.text,
"inventory_number": InvertarniiNomerResponse.text,
"cadastral_number": KadastroviiNomerResponse.text,
"date_of_the_last_overhaul": PosledniiKapitalniiRemontResponse.text,
"energy_efficiency": KlassEnergoResponse.text,
"house_balance": BalansPrinadlejnostiSel,
"definition_isystem": InformacionnayaSystemaResponse.text,
"ip_address_isystem": InformacionnayaIPadressResponse.text,
"last_energy_audit_at": EnergoAudiotResponse.text,
"number_of_sections": KolvoSekciiResponse.text,
"service_life_of_the_building": SrokSlujbZdaniyaResponse.text,
"depreciation": IznosMZHDResponse.text,
"house_walls": OblicovkaSel
]) { (result) in
print(result)
}
Try splitting your call to updaTeRecord(o_model:id:attrs:completion:) like this:
let myAttributes: [String: Any] = [
"street": ulicaResponse.text,
"parking_area": PlowadParkingaResponse.text,
"builded_at": GodPostroikiResponse.text,
//...
"service_life_of_the_building": SrokSlujbZdaniyaResponse.text,
"depreciation": IznosMZHDResponse.text,
"house_walls": OblicovkaSel
]
updaTeRecord(o_model: "property.building", id: 207, attrs: myAttributes) { (result) in
print(result)
}
Or this may work more stable (compile without similar issues) in most cases:
var myAttributes: [String: Any] = [:]
myAttributes["street"] = ulicaResponse.text
myAttributes["parking_area"] = PlowadParkingaResponse.text
myAttributes["builded_at"] = GodPostroikiResponse.text
//...
myAttributes["service_life_of_the_building"] = SrokSlujbZdaniyaResponse.text
myAttributes["depreciation"] = IznosMZHDResponse.text
myAttributes["house_walls"] = OblicovkaSel
updaTeRecord(o_model: "property.building", id: 207, attrs: myAttributes) { (result) in
print(result)
}
I am migrating my data from 1 format to another for a large update to one of my iOS apps. This means that when a user updates their application it migrates their data to a new location. This new location has much stricter rules and uses proper practices (basically when I first created the app I was a noob and there are bad practices currently in the database and this new location is for good data only).
I have everything migrating nicely and everything works except I need to do one last thing. The large dictionary that I save to the database (it uses firebase fyi) has -1.0 stored everywhere there should be a nil value (bad, I know). What I need to do is loop through the entire dictionary and remove any key where the value of that key is -1.0.
The Dictionary is of type [AnyHashable : Any] which is what firebase uses.
I have tried this so far.
if let data = dataDictionary as? [AnyHashable : Any] {
let foundItems = data.filter { $0.value as? Double == -1.0 }
print(foundItems)
}
the plan was to then loop through that found items array and remove any key from the data dictionary that contained it.
This is what the data dictionary looks like:
"-KpIdh_TQMG4fyfFgkdt" = {
assignments = {
"-KpIgH6uN19OpcuedYe1" = {
assignmentGoal = "-1";
assignmentName = "Information System Proposal";
assignmentResult = 100;
assignmentWeight = 5;
};
"-KpIgJnFlC6fhgS0NWxF" = {
assignmentGoal = "-1";
assignmentName = "Information System";
assignmentResult = "-1";
assignmentWeight = 35;
};
"-KpIgOGSAwg_VSpDWhWR" = {
assignmentGoal = "-1";
assignmentName = "Process Analysis";
assignmentResult = "-1";
assignmentWeight = 30;
};
"-KpIgPhu_3Zxw36xt3O4" = {
assignmentGoal = "-1";
assignmentName = Labs;
assignmentResult = "-1";
assignmentWeight = 10;
};
"-KpIgQoFEdRnLlMAq2VN" = {
assignmentGoal = "-1";
assignmentName = Exam;
assignmentResult = "-1";
assignmentWeight = 20;
};
};
paperColor = 22;
paperGoal = 95;
paperName = "Systems Analysis";
};
};
semesterCode = 17S2;
semesterGoal = 90;
semesterName = "2017 Semester Two";
};
};
and this is what it should look like
"-KpIdh_TQMG4fyfFgkdt" = {
assignments = {
"-KpIgH6uN19OpcuedYe1" = {
assignmentName = "Information System Proposal";
assignmentResult = 100;
assignmentWeight = 5;
};
"-KpIgJnFlC6fhgS0NWxF" = {
assignmentName = "Information System";
assignmentWeight = 35;
};
"-KpIgOGSAwg_VSpDWhWR" = {
assignmentName = "Process Analysis";
assignmentWeight = 30;
};
"-KpIgPhu_3Zxw36xt3O4" = {
assignmentName = Labs;
assignmentWeight = 10;
};
"-KpIgQoFEdRnLlMAq2VN" = {
assignmentName = Exam;
assignmentWeight = 20;
};
};
paperColor = 22;
paperGoal = 95;
paperName = "Systems Analysis";
};
};
semesterCode = 17S2;
semesterGoal = 90;
semesterName = "2017 Semester Two";
};
};
The solution I have is to map (iterate) over each parent key and assign it's child nodes to a variable child. Then test each child property (assignmentGoal, assignmentName etc) for either "-1" for the string and -1 for the ints. If it's a match, remove that key: value pair from child.
Then assign child back to the parent node.
let result: [Any] = dict.map { dictionary in
var d = dictionary
var child = d.value as Dictionary
if let goal = child["assignmentGoal"] as? String, goal == "-1" {
child.removeValue(forKey: "assignmentGoal")
}
if let name = child["assignmentName"] as? String, name == "-1" {
child.removeValue(forKey: "assignmentName")
}
if let result = child["assignmentResult"] as? Int, result == -1 {
child.removeValue(forKey: "assignmentResult")
}
if let weight = child["assignmentWeight"] as? Int, weight == -1 {
child.removeValue(forKey: "assignmentWeight")
}
d.value = child
return d
}
//show the output
for item in result {
print(item)
}
and the result output
(key: "-KpIgOGSAwg_VSpDWhWR",
value: ["assignmentName": "Process Analysis System", "assignmentWeight": 30])
(key: "-KpIgQoFEdRnLlMAq2VN",
value: ["assignmentName": "Exam", "assignmentWeight": 20])
(key: "-KpIgJnFlC6fhgS0NWxF",
value: ["assignmentName": "Information System", "assignmentGoal": "3", "assignmentWeight": 35])
(key: "-KpIgPhu_3Zxw36xt3O4",
value: ["assignmentName": "Labs", "assignmentWeight": 10])
(key: "-KpIgH6uN19OpcuedYe1",
value: ["assignmentName": "Information System Proposal", "assignmentResult": 100, "assignmentWeight": 5])
Code
func downloadimages (URL: NSURL) {
let request = NSMutableURLRequest ( URL: URL)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error ) in
guard error == nil else {
print("we have an error from Server")
return
}
var JSONData: AnyObject!
do {
JSONData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) /* as? [String:AnyObject?] */
} catch {
print (" We had a Parsing issue '\(data)'")
return
}
print(JSONData)// Doesn't print 'Optional' word?????
print(JSONData!)
if let something = JSONData!["photos"]{
print (something!)
print(something) // This prints the word 'Optional as well'
}
Output
//printed unwrapped--NOT GOOD! -- I didn't unwrap it with '!'
{
photos = {
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
};
stat = ok;
}
// unwrapped printed--Good!
{
photos = {
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
};
stat = ok;
}
//Unwrapped printed--Good
{
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
}
//wrapped and prints as optional--Good!
Optional({
page = 1;
pages = 622374;
perpage = 1;
photo = (
{
farm = 8;
id = 27765969370;
isfamily = 0;
isfriend = 0;
ispublic = 1;
owner = "8262787#N07";
secret = 6daeee7d68;
server = 7233;
title = "Stars, Planets and Lightning Bugs";
}
);
total = 622374;
})
My confusion is, if JSONData is an optional then why does it print as non-optional without ! and if it isn't an optional then why doesn't it give any error as Can not force unwrap value of non-optional type?. Since unwrapping a non-optional is error-ful!
My guess is that I am not understanding what my JSONData's type really is...
My guess is that I am not understanding what my JSONData's type really is...
I believe that is the point.
You've declared JSONData as AnyObject!, which is also known as ImplicitlyUnwrappedOptional<AnyObject>.
So, in your code print(JSONData), the value of JSONData is implicitly unwrapped.
And check the type of something in the Quick Help pane of your Xcode. It should be displayed as AnyObject?, aka Optional<AnyObject>.
One bad thing is that when implicit unwrapping occurs it doesn't get well-documented. You may need to know more about ImplicitlyUnwrappedOptional, before knowing exactly when that happens.
I searched and could not find an example of using a CFBinaryHeap from Swift code so I am posting my example as the answer below.
Here is an example that uses a CFBinaryHeap to store Foo structs from Swift, sorted by an integer property.
struct Foo {
var x : Int = 0
}
var callbacks = CFBinaryHeapCallBacks()
// <Foo> comparator
callbacks.compare = { (a,b,unused) in
let afoo : Foo = UnsafePointer<Foo>(a).memory
let bfoo : Foo = UnsafePointer<Foo>(b).memory
if ( afoo.x == bfoo.x ) { return CFComparisonResult.CompareEqualTo }
if ( afoo.x > bfoo.x ) { return CFComparisonResult.CompareGreaterThan }
return CFComparisonResult.CompareLessThan
}
let callbackPointer = UnsafeMutablePointer<CFBinaryHeapCallBacks>.alloc(1)
callbackPointer.initialize(callbacks)
var bh = CFBinaryHeapCreate(nil, 0, callbackPointer, nil)
var fooPointer : UnsafeMutablePointer<Foo>!
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 42))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 99))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 2))
CFBinaryHeapAddValue(bh, fooPointer)
var got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 2
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 42
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 99
CFBinaryHeapRemoveMinimumValue(bh)
Kindly see below code I am using to convert Mirth xml to JSON.
function E4XtoJSON(xml, ignored) {
var r, children = xml.*, attributes = xml.#*, length = children.length();
if(length == 0) {
r = xml.toString();
} else if(length == 1) {
var text = xml.text().toString();
if(text) {
r = text;
}
}
if(r == undefined) {
r = {};
for each (var child in children) {
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if(value) {
if(value.length) {
value.push(json);
} else {
r[name] = [value, json]
}
} else {
r[name] = json;
}
}
}
if(attributes.length()) {
var a = {}, c = 0;
for each (var attribute in attributes) {
var name = attribute.localName();
if(ignored && ignored.indexOf(name) == -1) {
a["_" + name] = attribute.toString();
c ++;
}
}
if(c) {
if(r) a._ = r;
return a;
}
}
return r;
}
My concern is
<AdditionalMessageInformationCount AdditionalMessageInformationCount="02"><AdditionalMessageInformationQualifier>01</AdditionalMessageInformationQualifier><AdditionalMessageInformation>MEMBER MUST USE MAIL ORDER.</AdditionalMessageInformation><AdditionalMessageInformationQualifier>02</AdditionalMessageInformationQualifier><AdditionalMessageInformation>PLAN LIMITATIONS EXCEEDED</AdditionalMessageInformation></AdditionalMessageInformationCount>
Here AdditionalMessageInformation elemt is used two times so function fails to create JSON.
Kindly help if anyone have converted XML in json usingg javascript code not any API
We've had success with this version:
function E4XtoJSON(xml, ignored){
var r, children = xml.*,
attributes = xml.# * ,
length = children.length();
if (length == 0)
{
r = xml.toString();
}
else if (length == 1)
{
var text = xml.text().toString();
if (text)
{
r = text;
}
}
if (r == undefined)
{
r = {};
for each(var child in children)
{
var name = child.localName();
var json = E4XtoJSON(child, ignored);
var value = r[name];
if (value)
{
if (value instanceof Array)
{
value.push(json);
}
else
{
r[name] = [value, json]
}
}
else
{
r[name] = json;
}
}
}
if (attributes.length())
{
var a = {},
c = 0;
for each(var attribute in attributes)
{
var name = attribute.localName();
if (ignored && ignored.indexOf(name) == -1)
{
a["_" + name] = attribute.toString();
c++;
}
}
if (c)
{
if (r) a._ = r;
return a;
}
}
return r;
}
With the release of Mirth Connect version 3.3.0, you can use Mirth Connect to set your channel's interior data type to JSON. This will all be done for you.