swift, back endless: Publish options - ios

I'm doing mini messenger. I have list of friends. And I want to when somebody send me some message, that person who send me message, go at the top of list of friends. How to do this? Below I'll show you me method which called when I send message.
func publishMessageAsync(message: String) {
let history = MessageHistory()
print("message is: \(message)")
history.message = message//text sms
history.user1 = Backendless.sharedInstance().userService.currentUser
history.user2 = self.friend.user2!
self.messageHistories.append(history)
self.chatTableView.reloadData()
MessageHistory is my class, which store history of messages))
Backendless.sharedInstance().messaging.publish(history.user2!.objectId, message: message,
response:{ ( messageStatus : MessageStatus!) -> () in
print("MessageStatus = \(messageStatus.status) ['\(messageStatus.messageId)']")
self.messageTextField.text = ""
self.messageTextField.resignFirstResponder()
// call function for saving
self.saveMessageHistory(message)
},
error: { ( fault : Fault!) -> () in
print("Server reported an error: \(fault)")
}
)
}

Related

unsubscribe channel not working in socketcluster with swift (iOS)

Unsubscribe channel not working on socketcluster.
I have to subscribe 20 channel. Now I want unsubscribe 10 channel. So We are use below code for subscribe.
// For subscribe
SoketManager.client.subscribeAck(channelName:"random") { (str, obj1, obj2) in
print ("Got data for channel", str)
}
// Listening to channel
SoketManager.client.onChannel(channelName:"random", ack: {
(channelName : String , data : AnyObject?) in
print ("Got data for channel", channelName, " object data is ", data ?? "")
})
We are use below code for unsubscribe.
// For unsubscribe
SoketManager.client.unsubscribeAck(channelName:"random", ack : {
(channelName : String, error : AnyObject?, data : AnyObject?) in
if (error is NSNull) {
print("Successfully unsubscribed to channel ", channelName)
} else {
print("Got error while unsubscribing ", error ?? "")
}
})
When I am call "unsubscribeAck" method always get error. Here is error.
{
message = "Failed to unsubscribe socket from the [object Object] channel - Socket YFaGYE5Tbu1_8we2AAAG tried to unsubscribe from an invalid channel name";
name = BrokerError;
}
Also I am trying with socketcluster demo as well but It not working for me.
Github link: https://github.com/sacOO7/socketcluster-client-swift
Appreciate your help.
Thanks

How to resolve: language content complaining with OneSignal in Swift

I'm using OneSignal to manage my push notifications. For some notifications, I'm receiving:
Notifications must have English language content
But I'm only sending everything in the english language...
oneSignal.postNotification(["headings" : ["en": "\(who)"],
"subtitle" : ["en": "\(subtitle)"],
"contents" : ["en": "\(contents)"],
"include_player_ids": [result]],
Who, subtitle, contents are Strings, result is the receiver ID. Most of the notifications are sent, for some I receive the error message.
Console:
> ERROR: Create notification failed
Error Domain=OneSignalError Code=400 "(null)" UserInfo={returned={
errors = (
" Notifications must have English language content"
);
}}
My complete function:
func sendPush(_ receiverID: String, _ who: String, _ didWhat: String, _ message: String?) {
var subtitle = ""
var contents = ""
if message != nil {
contents = message!
}
switch didWhat {
case "likePost":
subtitle = "liked your post"
case "commentPost":
subtitle = "commented on your post"
case "likeComment":
subtitle = "liked your comment"
case "message":
subtitle = "sent you a message"
case "friendsRequest":
subtitle = "sent you a friend request"
case "friendAccept":
subtitle = "accepted your friend request"
case "follow":
subtitle = "just followed you"
default:
break
}
getOneSignalPlayerID(receiverID, completion: { result in
oneSignal.postNotification(["headings" : ["en": "\(who)"],
"subtitle" : ["en": "\(subtitle)"],
"contents" : ["en": "\(contents)"],
"include_player_ids": [result]],
onSuccess: { (success) in
if success != nil {
print(success!)
}
}, onFailure: { (failure) in
if failure != nil {
print(failure!)
crashlyticsLog("getOneSignalPlayerID", failure!.localizedDescription)
}
})
})
}
What am I missing? Help is very appreciated.
I assume that one of the 4 fields is wrong. Wrong in this case can mean that it has sone illegal characters or characters in a non english coding. Print each field before posting the notification.
Another situation which raise this error may be caused because one of the fields is empty or nil. Again print them to a log before posting the notification.
Your JSON structure is wrong. This is a example of a code that works:
let objNotif = ["contents": ["en" : message], "include_player_ids": [userID!]]
//print(objNotif)
OneSignal.postNotification(objNotif, onSuccess: { (jsonSuccess) in
//Post OK
}) { (error) in
//Error
}
OneSignal Documentation:
https://documentation.onesignal.com/docs/ios-native-sdk

Quick blox chat message sending response is success but messages are not delivered to server

Just working with Quick blox Chat API though its interesting and fun but stuck horribly when coming to sending messages successfully to group.
I first created a ChatDialog(not public group) and its created with out any problems.Now i want to send messages to the ChatDialog.
This is the code at Client side in Swift :
let user = QBUUser()
user.ID = (QBSession.currentSession().currentUser?.ID)!
user.password = "*********"
QBChat.instance().connectWithUser(user) { (error: NSError?) -> Void in
if error == nil{
print("Success in connection")
self.chatGroup = QBChatDialog(dialogID:self.selectedChatGroup.chatGroupId, type: QBChatDialogType.Group)
self.chatGroup.occupantIDs = self.selectedChatGroup.opponents
self.chatGroup.joinWithCompletionBlock { (err) in
if err == nil{
print("Joined Succesfully")
let message: QBChatMessage = QBChatMessage()
message.text = "PRAISE THE LORD"
message.deliveredIDs = [(QBSession.currentSession().currentUser?.ID)!]
message.readIDs = [(QBSession.currentSession().currentUser?.ID)!]
message.markable = true
self.chatGroup.sendMessage(message, completionBlock: { (error: NSError?) -> Void in
if err == nil{
print(message.text)
print("Message sent Succesfully")
let resPage = QBResponsePage(limit:20, skip: 0)
QBRequest.messagesWithDialogID(self.selectedChatGroup.chatGroupId, extendedRequest: nil, forPage: resPage, successBlock: {(response: QBResponse, messages: [QBChatMessage]?, responcePage: QBResponsePage?) in
print("Messages count is \(messages?.count)")
}, errorBlock: {(response: QBResponse!) in
})
}else{
print(err?.localizedDescription)
}
});
}
else{
print(err?.localizedDescription)
}
}
}
}
This is the Response that i am getting back.i am pretty sure that logging to chat, connecting to group are successful. Even from the response given back from the API is also affirming that sending message is successful.But i am not able to see any messages in the Admin Panel at Quick blox. And also tried getting all the messages from the Chat dialog but its giving 0 messages.So my messages are not getting delivered.
Yah, got the solution from Quickblox API.This is what i missed in my code.
var params = NSMutableDictionary()
params["save_to_history"] = true
message.customParameters = params
Worked like a charm!

PubNub message text returning nil?

When I send a message using iOS to a PubNub channel, I can use the didReceiveMessage function to get that message and put it in my tableView. However, if I send a message via a client in the Dev Dashboard, message.data.message returns nil after I try to cast it as a String. Here's the function in question:
func client(client: PubNub, didReceiveMessage message: PNMessageResult) {
print("Received: %", message.data.message)
let newMessage:String? = message.data.message as? String
print(newMessage) // returns nil
self.messagesArray.append(newMessage!)
dispatch_async(dispatch_get_main_queue()) {
self.messageTableView.reloadData()
}
}
I get the following response in console from print("Received: %", message.data.message):
Received: % Optional({
text = test;
})
However, print(newMessage) is returning nil. What am I doing wrong?
Thanks!
EDIT: I'm getting the same thing when I try to get messages from the historyForChannel function.
//get history
pubNub.historyForChannel("channelname" as String, withCompletion: { (result, status) -> Void in
print(status)
if status == nil {
if result!.data.messages.count > 0 {
let historyMessages = result!.data.messages.description as? [String]
print(result)
for item in historyMessages!{
self.messagesArray.append(item)
}
}
}
})
historyMessages is nil, even though result prints:
Optional({
Operation = History;
Request = {
Authorization = "not set";
Method = GET;
Origin = "pubsub.pubnub.com";
"POST Body size" = 0;
Secure = YES;
URL = "...redacted";
UUID = "...redacted";
};
Response = {
"Processed data" = {
end = 14609023551682481;
messages = (
"technically ",
{
text = "Well..ok then";
},
hi,
"really ",
{
text = "Well..ok then";
},
How do I get the text from these returned messages?
From behaviour and fact what history fetch printed out status object means what you probably configured your client with cipherKey. That status object which you receive probably has category set to decryption error.
If you want to use encryption - you should use same key for all clients, or they won't be able to decrypt sent messages. If cipherKey is set, client automatically try to decrypt data and it will fail if regular text has been received.
Make sure both (console and iOS client) configured with same cipherKey or if you don't need it, make sure what it not set on any of clients.
Best regards,
Sergey.

How to retrieve the last message from Quickblox in iOS?

I send message to the chat dialog but I am not able to retreive the last messages.
How to get the the last messages from the chat dialog with a certain ID and and forwards it to the recipient for iOS?
If you have been joined the room, just access lastMessageText directly:
dialog.lastMessageText
Or get the last message with a certain ID using QBRequest:
QBRequest.messagesWithDialogID("ID",
extendedRequest: ["sort_desc" : "date_sent", "limit" : 1],
forPage: nil,
successBlock: { (response, messages, page) -> Void in
println(messages)
},
errorBlock: { (response) -> Void in
println(response)
}
)

Resources