xmppframework iphone Unable to add users into a group - objective-c

I am trying to making a chat application using XMPPFramework. I did complete connection setup. I am also able to do chat single user. I am also able to create a group for doing chat between multiple users. My problem is after created the group when i want to add users into a group is not working. Here the code I have used. Moreover, I didn't get any call this method didFetchModeratorsList:
Step-1
#pragma mark --- Create Room
- (void) createChatRoom:(NSString *)groupName{
if (!groupName)
{
return;
}
XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
NSString* roomID = [NSString stringWithFormat:#"%##conference.%#", groupName, CURRENT_HOST_NAME];
XMPPJID * roomJID = [XMPPJID jidWithString:roomID];
XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
jid:roomJID
dispatchQueue:dispatch_get_main_queue()];
[xmppRoom activate:xmppStream];
[xmppRoom addDelegate:self
delegateQueue:dispatch_get_main_queue()];
/*
NSXMLElement *history = [NSXMLElement elementWithName:#"history"];
[history addAttributeWithName:#" maxchars" stringValue:#"0"];
*/
[xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
history:nil
password:nil];
[self performSelector:#selector(ConfigureNewRoom:) withObject:nil afterDelay:3];
}
Step-2
#pragma mark --- addMemberInChatRoom
- (void) addMemberInChatRoom:(NSString*)roomName :(NSArray*)memberId{
NSLog(#"roomName: %#", roomName);
NSLog(#"memberId: %#", memberId);
XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
NSString* roomID = [NSString stringWithFormat:#"%##conference.%#", roomName, CURRENT_HOST_NAME];
XMPPJID * roomJID = [XMPPJID jidWithString:roomID];
XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
jid:roomJID
dispatchQueue:dispatch_get_main_queue()];
[xmppRoom activate:xmppStream];
[xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
history:nil
password:nil];
[self performSelector:#selector(ConfigureNewRoom:) withObject:nil afterDelay:1];
[xmppRoom inviteUsers:memberId withMessage:#"join this room"];
}
Step-3
#pragma mark --- This fuction is used configure new
- (void)ConfigureNewRoom:(XMPPRoom *)xmppRoom
{
[xmppRoom configureRoomUsingOptions:nil];
[xmppRoom fetchConfigurationForm];
//[xmppRoom fetchBanList];
[xmppRoom fetchMembersList];
//[xmppRoom fetchModeratorsList];
}
Step-4
- (void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
{
NSLog(#"%#: %# --- %#", THIS_FILE, THIS_METHOD, sender.roomJID.bare);
}

I think you are using two different instances.
Use something like below. This is working for me.
private var toBeCreatedRoom: XMPPRoom!
func createRoom(_ roomName: String) {
let roomStorage = XMPPRoomMemoryStorage()
let name = roomName + "#conference." + "hostName"
let roomJID = XMPPJID(string: name)
toBeCreatedRoom = XMPPRoom(roomStorage: roomStorage!, jid: roomJID!, dispatchQueue: DispatchQueue.main)
toBeCreatedRoom.addDelegate(self, delegateQueue: DispatchQueue.main)
toBeCreatedRoom.activate(self.xmppStream)
toBeCreatedRoom.join(usingNickname: "self.userName", history: nil, password: nil)
}
func inviteUsersToRoom(roomMembers: [XMPPJID]) {
if let room = toBeCreatedRoom {
for member in roomMembers {
let element = XMPPRoom.item(withAffiliation: "member", jid: member)
room.editPrivileges([element])
room.inviteUser(member, withMessage: "Hey, Welcome to the group!")
}
}
}

Related

Save config faild When I configure my iOS 8.0 VPN connection

I use Network Extension framework to configure and manage VPN connections. When I running my code ,it will log error message :"Save config faild[(null)]" before I finish install the config file. I’ve written my code as following:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.vpnManager = [NEVPNManager sharedManager];
[_vpnManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if (error) {
NSLog(#"Load config failed [%#]", error.localizedDescription);
return ;
}
// config IPSec protocol
NEVPNProtocolIKEv2 *p = _vpnManager.protocol;
if (p) {
}else{
p = [[NEVPNProtocolIKEv2 alloc]init];
}
p.username = #"qlvpn";
p.serverAddress = #"my serverAddress";
// get password persistent reference from keychain
p.passwordReference = [self searchKeychainCopyMatching:#"kd2014#"];
// If password doesn't exist in keychain, should create it beforehand.
if (!p.passwordReference) {
[self createKeychainValue:#"kd2014#" forIdentifier:#"kd2014#"];
p.passwordReference = [self searchKeychainCopyMatching:#"kd2014#"];
}
p.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
p.sharedSecretReference = [self searchKeychainCopyMatching:#"PSK"];
if (!p.sharedSecretReference) {
[self createKeychainValue:#"qlvpn_kd2014#" forIdentifier:#"PSK"];
p.sharedSecretReference = [self searchKeychainCopyMatching:#"PSK"];
}
p.localIdentifier = #"qlvpn.client";
p.remoteIdentifier = #"qlvpn.server";
p.useExtendedAuthentication = YES;
p.disconnectOnSleep = NO;
_vpnManager.protocol = p;
_vpnManager.localizedDescription = #"IKEv2 Demo";
[_vpnManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
NSLog(#"Save config faild[%#]",error.localizedDescription);
}];
}];
}
The keyChain method like this:
static NSString * const serviceName = #"qlvpn.vpn_config";
- (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier {
NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];
[searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
[searchDictionary setObject:serviceName forKey:(__bridge id)kSecAttrService];
return searchDictionary;
}
- (NSData *)searchKeychainCopyMatching:(NSString *)identifier {
NSMutableDictionary *searchDictionary = [self newSearchDictionary:identifier];
// Add search attributes
[searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
// Add search return types
// Must be persistent ref !!!!
[searchDictionary setObject:#YES forKey:(__bridge id)kSecReturnPersistentRef];
CFTypeRef result = NULL;
SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result);
return (__bridge_transfer NSData *)result;
}
- (BOOL)createKeychainValue:(NSString *)password forIdentifier:(NSString *)identifier {
NSMutableDictionary *dictionary = [self newSearchDictionary:identifier];
OSStatus status = SecItemDelete((__bridge CFDictionaryRef)dictionary);
NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
[dictionary setObject:passwordData forKey:(__bridge id)kSecValueData];
status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
if (status == errSecSuccess) {
return YES;
}
return NO;
}
So, I really don't know Why i cant save the config..
I couldn't save it unless I called both
loadAllFromPreferencesWithCompletionHandler
loadFromPreferencesWithCompletionHandler
and only then
saveToPreferencesWithCompletionHandler

Create Chat room with XMPPFramework openfire

I'm working on a chat App where I have to add group chat
functionality using XMPP Framework . I'm able to setup
peer-to-peer chatting. But when it comes to group chat ,I'm unable
to create a chat room. I know, this question has been asked many
times before, but I could not find any solution from that answers.
Here's my code for creating and configuring a chat room.
- (void)createChatRoom:(NSString *) newRoomName
{
NSString *jid=[NSString stringWithFormat:#"%##%#",newRoomName,kGroupChatDomain];
XMPPRoomMemoryStorage * _roomMemory = [[XMPPRoomMemoryStorage alloc]init];
XMPPJID * roomJID = [XMPPJID jidWithString:jid];
_xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:_roomMemory
jid:roomJID
dispatchQueue:dispatch_get_main_queue()];
NSString *nickName=[NSString stringWithFormat:#"%#chatRoom",newRoomName];
[_xmppRoom joinRoomUsingNickname:nickName
history:nil
password:nil];
[_xmppRoom activate:[AppDel xmppStream]];
[_xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
[_xmppRoom fetchConfigurationForm];
}
- (void)xmppRoomDidCreate:(XMPPRoom *)sender{
NSLog(#"didCreateChat Room method called");
}
- (void)xmppRoomDidJoin:(XMPPRoom *)sender{
NSLog(#"xmppRoomDidJoin method called ");
}
- (void)xmppRoom:(XMPPRoom *)sender didFetchConfigurationForm:(NSXMLElement *)configForm{
NSXMLElement *newConfig = [configForm copy];
NSArray* fields = [newConfig elementsForName:#"field"];
for (NSXMLElement *field in fields) {
NSString *var = [field attributeStringValueForName:#"var"];
if ([var isEqualToString:#"muc#roomconfig_persistentroom"]) {
[field removeChildAtIndex:0];
[field addChild:[NSXMLElement elementWithName:#"value" stringValue:#"1"]];
}
}
[sender configureRoomUsingOptions:newConfig];
}
Above is the code to create and configure the chat room. Before
calling this code, I'm connecting XMPP in viewDidLoad method. But
I'm unable to create a chat room. Code is not calling XMPPRoom
Delegate methods (xmppRoomDidCreate, xmppRoomDidJoin) I don't know
where I'm doing wrong, please correct me if there's any mistake in my
code. I could not even find any error in openfire logs. Please help me
resolving the issue. Any help will be appreciated.
Create room and if room already created you can easily join existing group using this code
- (void)createOrEnterRoom:(NSString *)groupName
{
BOOL flag=valueExistInGroup(groupName);
if (flag==TRUE) {
savevalueInGroup(groupName);
XMPPRoomMemoryStorage *roomStorage = [[XMPPRoomMemoryStorage alloc] init];
XMPPJID *roomJID = [XMPPJID jidWithString:[NSString stringWithFormat:#"%##conference.your_server_name",groupName]];
XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomStorage
jid:roomJID
dispatchQueue:dispatch_get_main_queue()];
[xmppRoom activate:xmppStream];
[xmppRoom addDelegate:self
delegateQueue:dispatch_get_main_queue()];
[xmppRoom joinRoomUsingNickname:xmppStream.myJID.user
history:nil
password:nil];
}
else
{
NSString *strJid=[AppSetting getUserId];
strJid=[strJid stringByAppendingFormat:#"#your_server_name"];
_xmppRoomStorage = [XMPPRoomHybridStorage sharedInstance];
XMPPJID *roomJid = [XMPPJID jidWithString:[NSString stringWithFormat:#"%##conference.52.10.97.23",groupName]];
XMPPRoom *xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:_xmppRoomStorage jid:roomJid];
[xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppRoom activate:xmppStream];
NSXMLElement *history = [NSXMLElement elementWithName:#"history"];
[history addAttributeWithName:#"maxstanzas" stringValue:#"10"];
[xmppRoom joinRoomUsingNickname:strJid history:nil];
}
}
- (void)xmppRoomDidJoin:(XMPPRoom *)sender{
[sender fetchConfigurationForm];
}
- (void)fetchConfigurationForm
{
dispatch_block_t block = ^{ #autoreleasepool {
XMPPLogTrace();
// <iq type='get'
// id='config1'
// to='coven#chat.shakespeare.lit'>
// <query xmlns='http://jabber.org/protocol/muc#owner'/>
// </iq>
NSString *fetchID = [xmppStream generateUUID];
NSXMLElement *query = [NSXMLElement elementWithName:#"query" xmlns:XMPPMUCOwnerNamespace];
XMPPIQ *iq = [XMPPIQ iqWithType:#"get" to:roomJID elementID:fetchID child:query];
[xmppStream sendElement:iq];
[responseTracker addID:fetchID
target:self
selector:#selector(handleConfigurationFormResponse:withInfo:)
timeout:60.0];
}};
if (dispatch_get_specific(moduleQueueTag))
block();
else
dispatch_async(moduleQueue, block);
}

iOS 7.1 BLE peripherial advertisment issue

I wrote an application with is advertising and scanning in the same time. It is working well, but I have an issue. After some time mz peripherial stop advertising.
I tried to restart but my phone and application it still not working.
Here is the peripheral implementation:
#implementation PeripheralManager
+ (PeripheralManager*)sharedInstance
{
static PeripheralManager *_sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedInstance = [[PeripheralManager alloc] init];
});
return _sharedInstance;
}
-(id)initWithUUID:(NSString *)UUID{
self = [super init];
if(self) {
self.UUID = UUID;
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}
return self;
}
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
return;
}
if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID] properties:CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsWriteable];
CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:self.UUID] primary:YES];
transferService.characteristics = #[_transferCharacteristic];
[_peripheralManager addService:transferService];
}
}
-(void)startAdvertisment{
[_peripheralManager startAdvertising:#{ CBAdvertisementDataServiceUUIDsKey : #[[CBUUID UUIDWithString:self.UUID]], CBAdvertisementDataLocalNameKey: PERIPHERAL_NAME}];
}

Create chatroom with XMPP framework and Ejabberd in iOS

Basically I'm trying to create a chatroom with all registered users on my domain using a ejabberd server. So a user can see all other online registered users on that domain when he enters the chatroom.
Until now I've only been able to make all the users 'friends / buddies' visible and deliver a notification when a friend goes online or offline with the help of the XMPP framework:
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {
// a buddy went offline/online
NSString *presenceType = [presence type]; // online/offline
NSString *myUsername = [[sender myJID] user];
NSString *presenceFromUser = [[presence from] user];
if (![presenceFromUser isEqualToString:myUsername]) {
if ([presenceType isEqualToString:#"available"]) {
[_chatDelegate newBuddyOnline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"chat.denederlandsewateren.nl"]];
} else if ([presenceType isEqualToString:#"unavailable"]) {
[_chatDelegate buddyWentOffline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"chat.denederlandsewateren.nl"]];
}
}
}
I'm able to get a list with all online registered users but I don't know how to notify the user when somebody goes online or offline.
- (void)getAllRegisteredUsers {
xmppRosterMemStorage = [[XMPPRosterMemoryStorage alloc] init];
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterMemStorage
dispatchQueue:dispatch_get_main_queue()];
[xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = false;
xmppRoster.autoFetchRoster = true;
[xmppRoster activate:xmppStream];
[xmppRoster fetchRoster];
NSError *error = [[NSError alloc] init];
NSXMLElement *query = [[NSXMLElement alloc] initWithXMLString:#"<query xmlns='http://jabber.org/protocol/disco#items' node='all users'/>"
error:&error];
XMPPIQ *iq = [XMPPIQ iqWithType:#"get"
to:[XMPPJID jidWithString:#"chat.denederlandsewateren.nl"]
elementID:[xmppStream generateUUID] child:query];
[xmppStream sendElement:iq];
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
NSXMLElement *queryElement = [iq elementForName: #"query" xmlns:
#"http://jabber.org/protocol/disco#items"];
if (queryElement) {
NSArray *itemElements = [queryElement elementsForName: #"item"];
NSMutableArray *mArray = [[NSMutableArray alloc] init];
for (int i=0; i<[itemElements count]; i++) {
NSString *jid=[[[itemElements objectAtIndex:i] attributeForName:#"jid"] stringValue];
[mArray addObject:jid];
[xmppRoster addUser:[XMPPJID jidWithString:jid] withNickname:[[jid componentsSeparatedByString:#"#"] objectAtIndex:0]];
}
}
How can I create a chatroom where the user can see all online registered users on one domain using a Ejabberd server and the XMPP framework?

How to add buddy/user in group in xmpp iphone?

I have wrote this code for creating room. Using this i had created room in openfire.
-(void)createGroup:(NSString*)groupName
{
XMPPRoomCoreDataStorage *rosterstorage = [[XMPPRoomCoreDataStorage alloc] init];
xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:rosterstorage jid:[XMPPJID jidWithString:[NSString stringWithFormat:#"%##conference.%#/%#",groupName,#"server",self.strUsername]] dispatchQueue:dispatch_get_main_queue()];
[xmppRoom activate:[self xmppStream]];
[xmppRoom joinRoomUsingNickname:#"nickname" history:nil];
[xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
[self performSelector:#selector(ConfigureNewRoom) withObject:nil afterDelay:5];
}
-(void)ConfigureNewRoom
{
[xmppRoom fetchConfigurationForm];
[xmppRoom configureRoomUsingOptions:nil];
}
Now I want to add buddy/users in the group. so how can i do this ? Thanks in advance.
// Using this it is done
XMPPRoomMemoryStorage *roomMemoryStorage = [[XMPPRoomMemoryStorage alloc] init];
NSString *strJid = [NSString stringWithFormat:#"%##conference.%#/%#",groupname,strHostname,self.strUsername];
self.xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:roomMemoryStorage jid:[XMPPJID jidWithString:strJid] dispatchQueue:dispatch_get_main_queue()];
[self.xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
[self.xmppRoom activate:self.xmppStream];
[self.xmppRoom joinRoomUsingNickname:self.strUsername history:nil];
//inviting
NSString *strInvitedUserName = [NSString stringWithFormat:#"%##%#",personName,strHostname];
[self.xmppRoom inviteUser:[XMPPJID jidWithString:strInvitedUserName] withMessage:message];
You can add it to your roster in this way:
[[[self appDelegate] xmppRoster] addUser:[XMPPJID jidWithString:#"userName"] withNickname:[NSString stringWithFormat:#"%# %#", firstName, lastName] groups:[NSArray arrayWithObjects:#"general", nil]];
and check it:
XMPPRosterCoreDataStorage *xmppRosterStorage = [[self appDelegate] xmppRosterStorage];
BOOL knownUser = [xmppRosterStorage userExistsWithJID:[XMPPJID jidWithString:#"userName"] xmppStream:[self xmppStream]];