indexOf of undefined error in parsing through cloud - parse-platform

Getting the error in below cloud function.
NSMutableDictionary * params = [NSMutableDictionary new];
params[#"user"] = _sender_ID;
params[#"recipientId"] = _owner_ID;
params[#"message"] = msgToSend;
[PFCloud callFunctionInBackground:#"sendPushToUser" withParameters:params block:^(id object, NSError *error) {
if (!error) {
// Push sent successfully
NSLog(#"msg posted!");
}
}];
error:
Error: TypeError: Cannot call method 'indexOf' of undefined
at main.js:15:35 (Code: 141, Version: 1.2.20)
Code for main.js is below.
Parse.Cloud.define("sendPushToUser", function(request, response) {
var senderUser = request.user;
var recipientUserId = request.params.recipientId;
var message = request.params.message;
// Validate that the sender is allowed to send to the recipient.
// For example each user has an array of objectIds of friends
if (senderUser.get("friendIds").indexOf(recipientUserId) === -1) {
response.error("The recipient is not the sender's friend, cannot send push.");
}
// Validate the message text.
// For example make sure it is under 140 characters
if (message.length > 140) {
// Truncate and add a ...
message = message.substring(0, 137) + "...";
}
// Send the push.
// Find devices associated with the recipient user
var recipientUser = new Parse.User();
recipientUser.id = recipientUserId;
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("user", recipientUser);
// Send the push notification to results of the query
Parse.Push.send({
where: pushQuery,
data: {
alert: message
}
}).then(function() {
response.success("Push was sent successfully.")
}, function(error) {
response.error("Push failed to send with error: " + error.message);
});
});
The above is the code written in main.js on cloud got the same from the link below. As far as i have understood from the error is that the problem is with the friendIds that's why it is not calling method 'indexOf'.
Got the idea from this link blog.

It would appear that, contrary to what is asserted in the comments, that senderUser (that is, request.user) does not, in fact, have an array of friends stored in friendIds.
Without any information as to the contents of senderUser (for example, you may have just mis-spelled the name of the field), the best we can do is respond to the error more gracefully by adding this before the if generating the error:
if (senderUser.get("friendIds") === undefined) {
response.error("The sender does not have any friends, cannot send push.");
}

Related

CNContactVCardSerialization keeps throwing an error

I can't find a solution for the fact that the line with: "CNContactVCardSerialization" keeps throwing an error. Any ideas on what can be wrong here and/or how to fix it? Getting the array with CNContacts works ok.
let contactStore = CNContactStore()
var contacts = [CNContact]()
var vcardFromContacts = NSData()
let fetchRequest = CNContactFetchRequest(keysToFetch:[CNContactVCardSerialization.descriptorForRequiredKeys()])
do{
try contactStore.enumerateContacts(with: fetchRequest, usingBlock: {
contact, cursor in
contacts.append(contact)})
} catch {
print(">>>[ERROR] Unable to get contacts: \(error)")
}
// Returns the vCard representation of the specified contacts
print(">>>[INFO ] Number of contacts found: \(contacts.count)")
do {
try vcardFromContacts = CNContactVCardSerialization.data(with: contacts) as NSData
} catch {
print(">>>[ERROR] Unable to create Vcard information: \(error)")
}

Marshalling objective c to nativescript js

Hello I'm trying to use the following cocoa pod for tcp functionality in ios:
https://cocoapods.org/pods/CocoaAsyncSocket
Im facing problems writing the marshalled js using this library
Here is an example (Objective C):
// The most common way to initialize an instance is simply like this:
socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if (![socket connectToHost:#"deusty.com" onPort:80 error:&err]) // Asynchronous!
{
// If there was an error, it's likely something like "already connected" or "no delegate set"
NSLog(#"I goofed: %#", err);
}
- (void)socket:(GCDAsyncSocket *)sender didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(#"Cool, I'm connected! That was easy.");
}
JSCODE:
// mainQueue var is to get dispatch_get_main_queue
var mainQueue = (function() {
var runloop = CFRunLoopGetMain();
return function(func) {
CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, func);
CFRunLoopWakeUp(runloop);
}
}());
var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(testerClass,mainQueue);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
console.log('Could not connect to mipbook');
console.log(e.value);
}
function socketDidConnectToHost(sock,host,port) {
console.log('connected to host');
}
The connect to port part is working fine, but the delegate instance method is not being called when the connection is successful.
Tried with this:
let delegate = ...
let dispatchQueue = dispatch_queue_create("test_queue", null);
let udp = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(delegate, dispatchQueue);
And it works fine. Should also work for GCDAsyncSocket.
For some reason dispatch_get_main_queue() is undefined.
Ok, I got it to work
The problem was with marshalling dispatch_get_main_queue(). I got my script to work by editing GDCAsyncSocket.m in the source of the pod used.
GDCAsyncSocket.m:
delegateQueue = dq;
change to
delegateQueue = dispatch_get_main_queue();
this way dispatch_get_main_queue() is no longer needed to be passed from the js side, its value is evaluated in the objective c library.
Here is the working JS code:
var tcpClientDelegate = NSObject.extend({
socketDidConnectToHostPort(sock,host,port) {
console.log('connected to host: '+host);
console.log('connected to port: '+port);
}
}, {
protocols: [GCDAsyncSocketDelegate]
});
var clientInstance = new tcpClientDelegate();
var tcpClient = GCDAsyncSocket.alloc().initWithDelegateDelegateQueue(clientInstance,null);
var e = new interop.Reference();
if (!tcpClient.connectToHostOnPortError('192.168.88.110',3333,e)) {
console.log('Could not connect to mipbook');
console.log(e.value);
}

How to send some count of POST/GET requests simultaneously?

I'm learning swift, trying to send 2 and more requests not one by one, but simultaneously. Is it possible with NSURLSession?
NSURLSession is asynchronous which means it is sent on a different thread and can be run multiple at once.
This link explains and gives an example on how to handle the response back on the main thread etc:
https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started
func sendRequest() {
let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
var dataTask: NSURLSessionDataTask?
let url = NSURL(string: "http://www.url.com")
dataTask = defaultSession.dataTaskWithURL(url!) {
data, response, error in
dispatch_async(dispatch_get_main_queue()) {
//Handle response
if let error = error {
//Error - handle 'error'
print(error.localizedDescription)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
//Success - handle 'data'
}
}
}
}
dataTask?.resume()
}
Hope this helps

Swift URL POST request function with returning values [duplicate]

I am currently trying to download, parse and print JSON from an URL.
So far I got to this point:
1) A class (JSONImport.swift), which handles my import:
var data = NSMutableData();
let url = NSURL(string:"http://headers.jsontest.com");
var session = NSURLSession.sharedSession();
var jsonError:NSError?;
var response : NSURLResponse?;
func startConnection(){
let task:NSURLSessionDataTask = session.dataTaskWithURL(url!, completionHandler:apiHandler)
task.resume();
self.apiHandler(data,response: response,error: jsonError);
}
func apiHandler(data:NSData?, response:NSURLResponse?, error:NSError?)
{
do{
let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
print(jsonData);
}
catch{
print("API error: \(error)");
}
}
My problem is, that the data in
do{
let jsonData : NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
print(jsonData);
}
remains empty.
When I debug,the connection starts successfully, with the given url as a parameter. But my jsonData variable doesn't get printed. Instead the catch block throws the error, stating that there is no data in my variable:
API error: Error Domain=NSCocoaErrorDomain Code=3840 "No value."
Can someone please help me with this?
What am I missing?
Thank you all very much in advance!
[Edited after switching from NSURL Connection to NSURLSession]
Here's an example on how to use NSURLSession with a very convenient "completion handler".
This function contains the network call and has the "completion handler" (a callback for when the data will be available):
func getDataFrom(urlString: String, completion: (data: NSData)->()) {
if let url = NSURL(string: urlString) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) in
// print(response)
if let data = data {
completion(data: data)
} else {
print(error?.localizedDescription)
}
}
task.resume()
} else {
// URL is invalid
}
}
You can use it like this, inside a new function, with a "trailing closure":
func apiManager() {
getDataFrom("http://headers.jsontest.com") { (data) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let jsonDict = json as? NSDictionary {
print(jsonDict)
} else {
// JSON data wasn't a dictionary
}
}
catch let error as NSError {
print("API error: \(error.debugDescription)")
}
}
}

Opentok sending signal ios

I got a problem with OpenTok, I got a session of OTSession and I want to call the method signalWithType so I can send a chat message.
In the start I have
var session : OTSession?
And then in my method where I want to send chat message from textField I get the error 'Could not find memember 'signalWithType'
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
let message = sendMessageField.text
sendMessageField.text = ""
var type = ""
var maybeError : OTError?
session?.signalWithType(type, string: message, connection: nil, error: maybeError)
if let error = maybeError {
println(error)
} else {
println("besked blev sendt")
}
return false
}
I can't find out why it says it as I pretty sure I got the right types and that.
I have not have other problems with calling methods from session..

Resources