In my application i Successfully Registered the User in openfire from the use of XMPP.
but when i Registered the User for first time it is coming offline.
and I have to Connect it again.
After disConnect and connect again it is working Correct.
I don't know why this happen.
My Code is
-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
NSLog(#"Did Connected pw:%#",_myTextViewCustom.text);
isOpen = YES;
NSError *error = nil;
[xmppStream authenticateWithPassword:_myTextViewCustom.text error:&error];
}
-(void)xmppStreamDidRegister:(XMPPStream *)sender
{
NSLog(#"xmppStreamDidRegister Method");
XMPPPresence *presence = [XMPPPresence presence];
[xmppStream sendElement:presence];
[xmppStream setMyJID:[XMPPJID jidWithString:[NSString stringWithFormat:#"%##server_Id",_jidTextView.text]]];
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
else
{
NSLog(#"Connection is in making");
}
[self goOnline];
}
- (void)goOnline {
XMPPPresence *presence = [XMPPPresence presence];
[xmppStream sendElement:presence];
XMPPSystemInputActivityMonitor *activiyMonitor = [[XMPPSystemInputActivityMonitor alloc]init];
activiyMonitor.inactivityTimeInterval = 1;
[activiyMonitor addDelegate:self delegateQueue:dispatch_get_main_queue()];
NSLog(#"Active : %d",[activiyMonitor isActive]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Successfull!!!"
message:[NSString stringWithFormat:#"Connected"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
Any types of Help will be great.
Thank you...
Once registration done. You need to Authenticate your self to openfire server.
[[self xmppStream] authenticateWithPassword:passwordString error:&error];
Once you call this method It will respond to
// get called on authenitcation successful
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
and
//Error while authenticating
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
And then
[self goOnline];
I solved this issue but not sure it's perfect or not so if you find another one then please tell me here.
i did change in
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
NSLog(#"didNotAuthenticate Method");
if(isRegister == TRUE)
{
[xmppStream registerWithPassword:_myTextViewCustom.text error:nil];
NSError * err = nil;
if(![xmppStream registerWithPassword:_myTextViewCustom.text error:&err])
{
NSLog(#"Error registering: %#", err);
[self performSelector:#selector(connect1) withObject:nil afterDelay:2.0];
}
}
}
-(void)connect1
{
isOpen = YES;
NSError *error = nil;
[xmppStream authenticateWithPassword:_myTextViewCustom.text error:&error];
}
I am calling Authentication again and it works but i don't think it's the final solution.
Related
I am connecting to XMPP server through XMPPFramework in IOS in objective C,
I had initialized the connection parameter in viewDidLoad method like this:
- (void)viewDidLoad {
[super viewDidLoad];
xmppStream = [[XMPPStream alloc] init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppStream.hostName = #"hostname";
xmppStream.hostPort = 5222;
NSString *username = #"name#domainname.net";
NSString *password = #"123456";
[xmppStream setMyJID:[XMPPJID jidWithString:username]];
NSError *error = nil;
if (![xmppStream oldSchoolSecureConnectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
}
And Trying to Authenticate in on button click like this:
- (IBAction)connectToXmpp:(id)sender {
NSLog(#"%hhd", [xmppStream isConnected]);
NSError *error = nil;
if (![xmppStream authenticateWithPassword:#"123456" error:&error]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't authenticate %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
[xmppStream sendElement:[XMPPPresence presence]];
}
But getting Error message on button click here is the error message:
Can some one please help me.Thanks.
#prem nath
In Above code you are trying to connect to server in - (void)viewDidLoad.
But You can authenticate with password after server connection established.
So - (void)xmppStreamDidConnect:(XMPPStream *)sender of XMPPStream Delegate is called when connection is established. You have to authenticate with server in XMPPStream Delegate.
I have complete code for send invitation when i click on button a pop up menu is appear,in the pop up menu say...
ERROR.
Game Requests are available to games.
and my code for invite friends are here:
NSDictionary *parameters = #{#"to":#""};
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:#"message aaya kya" title:#"app request"
parameters:parameters
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if(error)
{
NSLog(#"Some errorr: %#", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Invitiation Sending Failed" message:#"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
// [alrt release];
}
else
{
if (![resultURL query])
{
return;
}
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init];
for (NSString *paramKey in params)
{
if ([paramKey hasPrefix:#"to["])
{
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:#"request"])
{
NSLog(#"Request ID: %#", [params objectForKey:#"request"]);
}
if ([recipientIDs count] > 0)
{
//[self showMessage:#"Sent request successfully."];
//NSLog(#"Recipient ID(s): %#", recipientIDs);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Invitation(s) sent successfuly!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alrt show];
//[alrt release];
}
}
}
friendCache:nil];
}
so where I am wrong?
Please help me.
Thanks.
Ok,I understand if you want to send app request to your friends than you should use FBSDKAppInviteContent.
Here is the code:
FBSDKAppInviteContent *content =[[FBSDKAppInviteContent alloc] init];
content.appLinkURL = [NSURL URLWithString:#"Your_App_Id"];
content.previewImageURL = [NSURL URLWithString:#"Your_app_previewimage"];
[FBSDKAppInviteDialog showWithContent:content
delegate:self];
Here for Your_App_Id please refer to this link.
And it's delegate methods:
- (void)appInviteDialog:(FBSDKAppInviteDialog *)appInviteDialog didCompleteWithResults:(NSDictionary *)results{
if (results) {
}
}
- (void)appInviteDialog:(FBSDKAppInviteDialog *)appInviteDialog didFailWithError:(NSError *)error{
if (error) {
NSString *message = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?:
#"There was a problem sending the invite, please try again later.";
NSString *title = error.userInfo[FBSDKErrorLocalizedTitleKey] ?: #"Oops!";
[[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
}
Why don't you try FBSDKGameRequestContent(It will require Facebook SDK 4.0)?
Note: This will work only if your app category is Game in Facebook developer page.
Here is the code:
FBSDKGameRequestContent *gameRequestContent = [[FBSDKGameRequestContent alloc] init];
// Look at FBSDKGameRequestContent for futher optional properties
FBSDKGameRequestDialog *dialog = [[FBSDKGameRequestDialog alloc]init];
dialog.delegate = self;
dialog.content = gameRequestContent;
gameRequestContent.message = #"Become a Ninja!!!";
gameRequestContent.title = #"NinjaPan";
dialog.delegate = self;
dialog.content = gameRequestContent;
[dialog show];
And it's delegate methods:
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog didCompleteWithResults:(NSDictionary *)results{
if (results) {
}
}
- (void)gameRequestDialog:(FBSDKGameRequestDialog *)gameRequestDialog didFailWithError:(NSError *)error{
if (error) {
NSLog(#"%#",error.localizedDescription);
}
}
- (void)gameRequestDialogDidCancel:(FBSDKGameRequestDialog *)gameRequestDialog{
NSLog(#"Cancelled by user");
}
i am stuck in one issue.when i register brand new User on my ejjaber server host it completely register on it after the it didn't get invoke in xmpp the delegate of like:
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender;
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error;
i am using the DidConnect of xmpp below:
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSString *strPassward= [[NSUserDefaults standardUserDefaults]stringForKey:#"userPassword"];
NSError *error = nil;
NSError *err;
if(![[self xmppStream] registerWithPassword:strPassward error:&err])
{
XMPPPresence *presence = [XMPPPresence presenceWithType:#"available"];
[sender sendElement:presence];
}
else
{
[self goOnline];
NSLog(#"%s", __FUNCTION__);
XMPPPresence *presence = [XMPPPresence presenceWithType:#"available"];
[sender sendElement:presence];
}
[[self xmppStream] authenticateWithPassword:strPassward error:&error];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
XMPPPresence *presence = [XMPPPresence presence];
[xmppStream sendElement:presence];
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:#"kXMPPmyJID"];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:#"kXMPPmyPassword"];
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
else
{
NSLog(#"Connection is in making");
}
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
NSLog(#"Did not authenticate");
NSLog(#"didNotAuthenticate Method");
if(isRegister == TRUE)
{
[xmppStream registerWithPassword:password error:nil];
NSError * err = nil;
if(![xmppStream registerWithPassword:password error:&err])
{
NSLog(#"Error registering: %#", err);
[self performSelector:#selector(connect1) withObject:nil afterDelay:1.0];
}
}
}
- (void)goOnline
{
XMPPPresence *presence = [XMPPPresence presence];
[[self xmppStream] sendElement:presence];
XMPPSystemInputActivityMonitor *activiyMonitor = [[XMPPSystemInputActivityMonitor alloc]init];
activiyMonitor.inactivityTimeInterval = 1;
[activiyMonitor addDelegate:self delegateQueue:dispatch_get_main_queue()];
NSLog(#"Active : %d",[activiyMonitor isActive]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Successfull!!!"
message:[NSString stringWithFormat:#"Connected"]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}
-(void)connect1
{
//isOpen = YES;
NSError *error = nil;
[[self xmppStream] authenticateWithPassword:password error:&error];
}
Any idea on how to resolve this issue will be very helpful. Let me know if you need any additional info.
Thanks for your time and help.
Hi I am using facebook SDK 3.8 in my project. and using HelloFaceBookSample Code in my app but in my app i have no login button of facebook. I have implemented login flow of facebook and after login i have post on facebook. Now Post Status working fine but when i post image on facebook it give me error of
an attempt was made reauthorize permissions on an unopened session in ios
Code :
-(void) clickButtonFacebookUsingSDK
{
if (!appdelegate.session.isOpen)
{
appdelegate.session = [[FBSession alloc] init];
[appdelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(appdelegate.session.isOpen)
{
NSLog(#"calling postdata when session is not open******");
[self postData];
}
}];
}
else
{
NSLog(#"calling postdata when session is open******");
[self postData];
}
}
-(void) postData
{
[self showingActivityIndicator];
UIImage *img = [UIImage imageNamed:#"abc.jpg"];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
FBRequest *req = [FBRequest requestForUploadPhoto:img];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:message3, #"message", nil]];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [self showAlert:#"Photo Post" result:result error:error];
[self showAlert:#"Photo Post" result:result resulterror:error];
if (FBSession.activeSession.isOpen) {
}
}];
[connection start];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message result:(id)result resulterror:(NSError *)error
{
NSString *alertMsg;
NSString *alertTitle;
if (error)
{
alertTitle = #"Error";
// Since we use FBRequestConnectionErrorBehaviorAlertUser,
// we do not need to surface our own alert view if there is an
// an fberrorUserMessage unless the session is closed.
if (FBSession.activeSession.isOpen) {
alertTitle = #"Error";
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
}
else
{
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissActivityIndicator];
}
}
it gives me error in performPublishAction method.
can anyone tell me what is the problem . i have a lot of search and also found many solution but no one work. Please help. Thanks in advance.
I think that you have to set to FBSession what is its active session :
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
I have developed the XMPP Chat client for iOS and now I'm researching for how to do a new user registration from iOS itself. Can anyone help with the methods used to register a new user. As it needs to communicate with the Server and store the username and password to the server database. Please help I'm searching it from 2 days.
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:[NSXMLElement elementWithName:#"username" stringValue:#"venkat"]];
[elements addObject:[NSXMLElement elementWithName:#"password" stringValue:#"dfds"]];
[elements addObject:[NSXMLElement elementWithName:#"name" stringValue:#"eref defg"]];
[elements addObject:[NSXMLElement elementWithName:#"accountType" stringValue:#"3"]];
[elements addObject:[NSXMLElement elementWithName:#"deviceToken" stringValue:#"adfg3455bhjdfsdfhhaqjdsjd635n"]];
[elements addObject:[NSXMLElement elementWithName:#"email" stringValue:#"abc#bbc.com"]];
[[[self appDelegate] xmppStream] registerWithElements:elements error:nil];
We will know whether the registration is successful or not using the below delegates.
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration" message:#"Registration Successful!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
DDXMLElement *errorXML = [error elementForName:#"error"];
NSString *errorCode = [[errorXML attributeForName:#"code"] stringValue];
NSString *regError = [NSString stringWithFormat:#"ERROR :- %#",error.description];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration Failed!" message:regError delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
if([errorCode isEqualToString:#"409"]){
[alert setMessage:#"Username Already Exists!"];
}
[alert show];
}
This solution HAS WORKED for me
NSString *username = #"rohit#XMPP_SERVER_IP_HERE"; // OR [NSString stringWithFormat:#"%##%#",username,XMPP_BASE_URL]]
NSString *password = #"SOME_PASSWORD";
AppDelegate *del = (AppDelegate *)[[UIApplication sharedApplication] delegate];
del.xmppStream.myJID = [XMPPJID jidWithString:username];
NSLog(#"Does supports registration %ub ", );
NSLog(#"Attempting registration for username %#",del.xmppStream.myJID.bare);
if (del.xmppStream.supportsInBandRegistration) {
NSError *error = nil;
if (![del.xmppStream registerWithPassword:password error:&error])
{
NSLog(#"Oops, I forgot something: %#", error);
}else{
NSLog(#"No Error");
}
}
// You will get delegate called after registrations in either success or failure case. These delegates are in XMPPStream class
// - (void)xmppStreamDidRegister:(XMPPStream *)sender
//- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
New user can register at XMPP server from iOS by two methods as
Methode 1.) By In band Registration (In-band registration means that users that do not have an account on your server can register one using the XMPP protocol itself, so the registration stays "in band", inside the same protocol you're already using.) you have to use XEP-0077 extension.
And your server should also have to support In band Registration.
Use these steps for In band Registration
step 1: connect with xmppStream
- (BOOL)connectAndRegister
{
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = #"abc#XMPP_SERVER_IP_HERE"; // OR [NSString stringWithFormat:#"%##%#",username,XMPP_BASE_URL]]
NSString *myPassword = #"SOME_PASSWORD";
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// Replace me with the proper JID and password:
// myJID = #"user#gmail.com/xmppframework";
// myPassword = #"";
if (myJID == nil || myPassword == nil) {
DDLogWarn(#"JID and password must be set before connecting!");
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connect:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error connecting"
message:#"See console for error details."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
NSString *password declare at #interface part of your file
step 2: When xmppStream Delegate - (void)xmppStreamDidConnect:(XMPPStream *)sender call
step 3: Start register via In-Band Registration as
- (void)xmppStreamDidConnect:(XMPPStream *)sender{
DDLogVerbose(#"%#: %#", THIS_FILE, THIS_METHOD);
[[NSNotificationCenter defaultCenter] postNotificationName:XMPPStreamStatusDidConnectNotification
object:nil
userInfo:nil];
_isXmppConnected = YES;
NSError *error = nil;
DDLogVerbose(#"Start register via In-Band Registration...");
if (xmppStream.supportsInBandRegistration) {
if (![xmppStream registerWithPassword:password error:&error]) {
NSLog(#"Oops, I forgot something: %#", error);
}else {
NSLog(#"No Error");
}
}
// [_xmppStream authenticateWithPassword:password error:&error];
}
step 4: Check registration success or failure by XMPPStream delegate
- (void)xmppStreamDidRegister:(XMPPStream *)sender
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
Methode 2.) By XMPP Rest Api on the openFire server installed a plugin (Rest Api plugin) that allows normal registration.
Use these steps for Rest Api Registration
step 1: Install Rest Api plugin on server
step 2: Configure server for Rest Api as server -> server settings -> Rest Api then enable it.
You can use "Secret key auth" for secure user registration, so copy that from openfire server and use when rest api is called for registration.
step 3: Call Rest Api for registration
-(void)CreateUserAPI
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"abc",#"username",#"SOME_PASSWORD",#"password",#"abc-nickname",#"name",#"abc#example.com",#"email", nil];
NSData* RequestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:[NSString stringWithFormat:#"%#users",RESTAPISERVER]]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:AuthenticationToken forHTTPHeaderField:#"Authorization"];
[request setHTTPBody: RequestData];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
if (!error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ([httpResponse statusCode]==201)
{
NSLog(#"Registration Successful");
}else
{
NSLog(#"Registration failed");
}
}else
{
NSLog(#"Try again for registration");
}
}] resume];
}
RESTAPISERVER is a Rest api url string.
AuthenticationToken is a "Secret key auth" (copy from openfire server)