Passing an object to a Meteor method using swiftDDP - ios

I am trying to use meteor and iOS for a project of mine. My problem is that I am trying to connect to a meteor function using the swiftDDP library. When sending data it is sent in the wrong format. How can I pass an object from iOS that Meteor (running in js) will accept? Is there a way to do this using a string? I have working javascript code that calls the same functions how would I pass the same form of data from iOS/swift?
Javascript
Meteor.call('xxx', {a: 1, b: 2, c: "some text"});
IOS (passes anyobject)
Meteor.call("xxx", ?? )

Solved this I created a object in this format on IOS swift let data: [String : AnyObject] = [ "time" : {time object} "foo" : "1", "blah" : "1", ] Then simply called Meteor.call("events.add", params: [data]) { result, error in // Do something with the method result NSLog("call worked") }

Related

Swift & Firestore - appending dictionary to nested array using .arrayUnion()

I am creating a chat application where a user can start multiple chats with a different person (just like the rest of the other chat apps). I'm using Swift with Cloud Firestore.
My database design is the following:
Chat collection: [
"chatMember": ["member1", "member2"],
"createdAt" : Date().timeIntervalSince1970,
"meesages" : []
]
One chat room will have 'messages' array and it will have message dictionaries aka an object.
Below code is where I am trying to append the message dictionary to the messages array.
The Firebase doc introduces .arrayUnion() <LINK to the document>.
But it gives me an error saying,
"Contextual type '[Any]' cannot be used with dictionary literal"
#IBAction func sendBtnPressed(_ sender: UIButton) {
if let messageBody = messageField.text, let messageSender = Auth.auth().currentUser?.email {
db.collection("collectionName").document("docName").updateData([
// FieldValue.arrayUnion() does not work for this case.
K.FB.messages: FieldValue.arrayUnion([
"sender": messageSender,
"content": messageBody,
"createdAt": Date().timeIntervalSince1970
])
]) { ... closure }
}
}
I can't find any information specifically related to Swift's appending Dictionary to nested array in the Cloud Firestore.
I found a very similar case on YouTube <https://youtu.be/LKAXg2drQJQ> but this is made with Angular which uses an object with { ...curly bracket}. FieldValue.arrayUnion() seems to work on other languages but not Swift.
It'd be awesome if someone who has resolved this issue would help me out.
Thank you in advance.
So basically what you're saying with this code:
K.FB.messages: FieldValue.arrayUnion([
"sender": messageSender,
"content": messageBody,
"createdAt": Date().timeIntervalSince1970
])
is that you want to append dictionary to array with name that is in K.FB.messages constant. But you don't really want to do that and it isn't even possible. You want to append array of dictionaries to array. This means that you must enclose your dictionary in a square brackets. Like shown below:
K.FB.messages: FieldValue.arrayUnion([[
"sender": messageSender,
"content": messageBody,
"createdAt": Date().timeIntervalSince1970
]])

Fresh POSTMAN 4.9.3, env variable bug or feature?

My requests return BigInteger id. I use these lines to extract them from response:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", data.id);
I updated Postman App to version 4.9.3 and caught a problem with environmental variables.
For example, I receive id="9141989209013199260" and expect app to save "9141989209013199260", but i'm getting "9141989209013199000" instead. Any ideas?
var str = '{ "id": 9146756954251460484, "name" : "test" }';
str = str.replace(/\d{19}/, '"$&"');
var obj = JSON.parse(str);
alert(obj.id);
Done!

Swift, Firebase, Flashlight, how to store arrays?

I am currently trying to use Firebase, Flashlight and Swift to create an search function to retrieve a random object from my realtime database.
I am trying to perform the following query to Firebase at /search/request
var searchSettings : [Any] = []
if Settings.searchPackage != 99 {
searchSettings.append(["match" : Settings.searchPackage])
}
if Settings.searchCountry != .world {
if let region = Locale.current.regionCode {
searchSettings.append(["match" : region])
}
}
if Settings.searchGender != .All {
searchSettings.append(["match" : Settings.searchGender.rawValue])
}
let postData = [
"index" : "firebase",
"type" : "test",
"body" : [
"query" : searchSettings
]
] as [String : Any]
ref.setValue(postData, withCompletionBlock: { (error, reference) in
if error == nil {
FIRDatabase.database().reference().child("search/response").child(ref.key).observeSingleEvent(of: .childAdded, with: { (snapshot) in
if snapshot.exists() {
print("found random snapshot based on settings \(snapshot)")
}
})
}
})
The problem is, as Firebase described in the documentation it does currently support Arrays, therefor the content of "query" will be:
Flashlight will throw an error because it expects the "query" to contain "match" fields and not the indexes of an array of them.
How would I fix this? I want to be able to search based on multiple fields.
Technically, Flashlight doesn't care at all what you put inside the body tag; it simply passes it on to ElasticSearch. So if there is an error generated about the format, it's ElasticSearch that's doing the complaining.
What you're probably running into here is either a) ElasticSearch doesn't like that syntax, or Firebase's array-like behaviors are converting the array to an object.
Note that Flashlight will allow you to pass a JSON string in place of body. So if this is a result of the array-like behaviors, you can JSON.stringify() the query before passing it into ES, and it will come out the other end as intended.
If the problem is the ES syntax (as it appears to me) then you can simply run the queries directly against ES until they work, and then modify your client to submit correct syntax accordingly.
Take a look at this gist:
BodyQuery in Swift
I wrote this in my Android application project and I'm using this to build queries for ES. Here is equivalent in Java for Android ElasticSearch needs a json query, and you can create it easily using Maps (Android)/Dictionaries (iOS). Enjoy :)

How to extract data from JSON with Alamofire

I use the Alamofire library this way:
Alamofire.request(.POST, "http://www.somesample.com/getData.php", parameters: ["user":"charles"]).responseJSON{jsonData in
var theData = jsonData.result.value
If I debug print the theData variable, it throws something like:
[
{
"userId" : "61",
"userPicture" : "147884767502.jpg",
"wasId" : "80",
"favorite" : "0",
"message" : "how are you?",
"username" : "paco",
"date" : "13\/10\/2015 03:44PM",
"userPhrase" : "hello"
"repliesNumber" : 2
},
{
"userId" : "3",
"userPicture" : "149181897286.jpg",
"wasId" : "5",
"favorite" : "0",
"message" : "let's go!",
"username" : "loliFlower",
"date" : "30\/08\/2015 07:48PM",
"userPhrase" : "ciiiii!",
"repliesNumber" : 3
}
]
I usually use SwiftyJSON so I write (even I use a for loop to walk to every single index of the array the SwiftyJSON makes:
var myData = JSON(theData.result.value)
print(myData[0]["username"].stringValue)
But what if I don't want to use SwiftyJSON library anymore? what is the native way to do this?
I recommend that you use code generation to create native models out of the json response, this will save your time of parsing by hand and reduce the risk of errors due to mistaken keys, all elements will be accessible by model properties, this will be purely native and the models will make more sense rather checking the keys. Check http://www.json4swift.com and let me know if you require further help in initiating the object from your json response. (make sure you enter the actual json response and not the printed object as that in your question)

How to access data in array in JSON

JSON:
{
"projects":[
{
"id":113,
"name":"Mobile app Android",
"description":"",
"created_on":"2014-10-03T16:53:56+02:00",
"updated_on":"2014-12-03T16:59:45+01:00"
},
{
"id":142,
"name":"Mobile app iOS",
"created_on":"2014-12-11T18:30:55+01:00",
"updated_on":"2014-12-11T18:30:55+01:00"
},
{
"id":52,
"name":"Test project",
"identifier":"grafikr",
"description":"",
"created_on":"2013-10-14T17:21:33+02:00",
"updated_on":"2014-10-10T17:40:47+02:00"
},
{
"id":37,
"name":"Sample project",
"identifier":"grafikf",
"description":"",
"created_on":"2013-09-18T16:31:25+02:00",
"updated_on":"2013-09-26T13:11:58+02:00"
}
],
"total_count":4,
"offset":0,
"limit":25
}
It is easy to access for example name of the first project (with name Mobile app Android) by var name = json["projects"][0]["name"].stringValue
But how do I access all names in SwiftyJSON? If I make a variable var projects = json["projects"], it gives me:
[
{
"id" : 113,
"created_on" : "2014-10-03T16:53:56+02:00",
"name" : "Mobile app Android",
"description" : "",
"updated_on" : "2014-12-03T16:59:45+01:00"
},
...
Now I don't have a problem with making a NSDictionary from data anymore, but this drives me crazy.
There's a lot going on in your code sample—perhaps too much to be addressed by a single Stack Overflow question / answer.
I would strongly recommend going back to Apple's resources for Swift and iOS application patterns. Topics to revisit would include synchronous versus asynchronous programming, authentication, and using data sources with table views.
This should probably work. Your json also contains "total_count", which looking at it, I assume that's the count of the number of projects. Pull that count out, loop over till the count and fetch the name.
var names = [String]()
let count = json["total_count"].int
for index in 0..<count {
let name = json["projects"][index]["name"].string
names.append(name)
}
Why not use SwiftyJSON the Swifty way???
Try this:
let names = json["projects"].arrayValue.map {
$0["name"].stringValue
}

Resources