need XMPP Framework - iphone

I am working on ejabberd setup, i configured the server successfully, But in the client side we need XMPP Framework for this,
I Googled i got the following links
http://deusty.blogspot.in/2008/08/xmppframework-on-iphone.html
http://iphone4developer.blogspot.in/2011/07/how-to-add-xmpp-in-your-ios-project.html
I downloaded the robbiehanson / XMPPFramework but it throws errors, and some links gives me 404 error(they removed)
I downloaded the jabber client from this link (https://github.com/funkyboy/Building-a-Jabber-client-for-iOS) but the xmpp framework files throws errors(those are already deleted) from the app
I got one sample that is iPhoneXMPP sample but it throws error that is "Unable to connect to server. Check xmppStream.hostName" i given my host name in willSecureWithSettings method
Doubts:
1)Please Guide me to download the proper XMPP Framework with out errors
2)How to Configure ejabber client side?
Please guide me
Thanks a lot in advance

I downloaded the robbiehanson/XMPPFramework around 6 months back from this link: https://github.com/robbiehanson/XMPPFramework . I followed the steps that are mentioned in Getting Started section. It didn't throw any error. Just try to follow these steps to setup the xmppframework with your application.
In sample app, I found the function setupStream() that I am calling when I start my application. In this function I am creating an xmppStream and activating different modules that are needed in my application. e.g
xmppStream = [[XMPPStream alloc] init];
// Activate xmpp modules after creating them
[xmppReconnect activate:xmppStream];
[xmppRoster activate:xmppStream];
[xmppvCardTempModule activate:xmppStream];
[xmppvCardAvatarModule activate:xmppStream];
[xmppCapabilities activate:xmppStream];
// Add ourself as a delegate to anything we may be interested in
[xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
[xmppStream setHostName:XMPPHOST];
[xmppStream setHostPort:5222];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = NO;
After setting the stream, you need to do authentication like this:
- (BOOL)connect:(NSString *)myJID //username registered with server
{
if (![xmppStream isDisconnected]) {
return YES;
}
if (myJID == nil) {
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
NSError *error = nil;
if (![xmppStream connect:&error])
{
if(DEBUG)
{
NSLog(#"ERROR: Not connected to XMPP Server");
}
DDLogError(#"Error connecting: %#", error);
return NO;
}
return YES;
}
This function will be called by the framework and pass the password here:
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
if(sender == xmppStream)
{
//DDLogVerbose(#"In xmppStream: %#: %#", THIS_FILE, THIS_METHOD);
isXmppConnected = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(#"Error authenticating: %#", error);
}
}
}
Now if user is authenticated, this function will be called:
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
if(sender == xmppStream)
{
[self goOnline];
}
}
goOnline will send user's presence to server:
- (void)goOnline
{
XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
[xmppStream sendElement:presence];
}
Now you can send/receive the message/presence etc.

You will find a nice - complet - tutorial here: http://mobile.tutsplus.com/tutorials/iphone/building-a-jabber-client-for-ios-server-setup/

Related

XMPP authentication returns yes but XMPPStreamDidAuthenticate never called

I am trying to create an application that implements Facebook Chat. I have set up all of the XMPP stuff correctly to the best of my knowledge, but I cannot get it to work.
After the user has logged in and been authenticated to Facebook (via FBSession) I try to connect to the chat service. Here is where the XMPP comes in:
-(void)connect
{
[self setupStream];
NSError *err;
[self.xmppStream connectWithTimeout:10.00 error:&err];
}
-(void)setupStream
{
_xmppStream = [[XMPPStream alloc] initWithFacebookAppId:FACEBOOK_APP_ID];
[self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender {
NSError *error;
NSError *err;
[self.xmppStream secureConnection:&err];
bool authed = [self.xmppStream authenticateWithFacebookAccessToken: FBSession.activeSession.accessTokenData.accessToken error:&error];
NSLog(#"%#", err);
NSLog(#"%#", [self.xmppStream authenticationDate]);
NSLog(#"%d, %#", authed, error);
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {
NSLog(#"did authenticate");
[self goOnline];
}
When running the above, everything seems to go fine: xmppStreamDidConnect is called after a short wait and authed always returns YES and its error is always null.
However, secureConnection returns Error Domain=XMPPStreamErrorDomain Code=1 "Please wait until the stream is connected." UserInfo=0xb23dc30 {NSLocalizedDescription=Please wait until the stream is connected.} The authenticationDate is always null as well. Also, none of the other delegate methods are ever called, including xmppStreamDidAuthenticate. What am I doing wrong?
I have finally found my answer!! Here it is, in case anyone else runs in to the same problem as me:
When calling openActiveSessionWithReadPermissions:allowLoginUI:completionHandler: the FBSession object does not actually communicate with the Facebook servers or attempt to authenticate with them, it simply loads the previous authenticationToken. In my case, this token had become invalid, but I did not realize it and nothing was there to tell me. I finally figured it out by logging the token and putting it in Facebook's Access Token Debugger. To check if your token is valid, you must call [FBSession renewSystemCredentials:] and await the result. Then you can determine if you need to manually closeAndClearTokenInformation before attempting to create a new token.

Why can't I authenticate to Facebook Chat in my iOS application?

I have been scouring the internet trying to find a solution to this problem. I understand the basic idea on how it is supposed to work, but I can't get the implementation to work and I can't find any decent examples to help me. So far I have successfully been able to log in a user using the iOS 6 authentication mechanism, but I cannot figure out how to authenticate a user to the Jabber server from there. Here is what I have:
After the user has logged in connect is called
-(void)connect
{
[self setupStream];
NSError *error = nil;
[_xmppStream authenticateWithFacebookAccessToken: FBSession.activeSession.accessTokenData.accessToken error:&error];
NSLog(#"%#", error);
[NSString stringWithFormat:#"%#", self];
}
-(void)newSetupStream
{
_xmppStream = [[XMPPStream alloc] initWithFacebookAppId:#"611051652253156"];
#if !TARGET_IPHONE_SIMULATOR
{
xmppStream.enableBackgroundingOnSocket = YES;
}
#endif
_xmppReconnect = [[XMPPReconnect alloc] init];
_xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
_xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:_xmppRosterStorage];
_xmppRoster.autoFetchRoster = YES;
_xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
_xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
_xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:_xmppvCardStorage];
_xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:_xmppvCardTempModule];
_xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
_xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:_xmppCapabilitiesStorage];
_xmppCapabilities.autoFetchHashedCapabilities = YES;
_xmppCapabilities.autoFetchNonHashedCapabilities = NO;
[_xmppReconnect activate:_xmppStream];
[_xmppRoster activate:_xmppStream];
[_xmppvCardTempModule activate:_xmppStream];
[_xmppvCardAvatarModule activate:_xmppStream];
[_xmppCapabilities activate:_xmppStream];
[_xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[_xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
No matter what I try it always returns the same error: Error Domain=XMPPStreamErrorDomain Code=4 "The server does not support X-FACEBOOK-PLATFORM authentication."
I am not incredibly familiar with either XMPP or the Facebook API so I'm sure there is something simple I am missing, but I have been working on this forever and been unable to make any progress. Any ideas?
I found my answer. In case anyone else runs into this same problem: I never actually told my XMPPStream to connect. I had tried all of the connect methods before, but they never worked. I now realize that I simply did not wait for them to finish connecting. Here is what I ended up changing:
NSError *error;
NSError *err;
[_xmppStream connectWithTimeout:10.00 error:&err];
[_xmppStream authenticateWithFacebookAccessToken: FBSession.activeSession.accessTokenData.accessToken error:&error];
while (error)
{
sleep(1);
[_xmppStream authenticateWithFacebookAccessToken: FBSession.activeSession.accessTokenData.accessToken error:&error];
}
I realize that it's not the most elegant solution, but it works.
make sure you use chat.facebook.com or facebook.com as the host name.
You must also open session with xmpp_login permission.
For me the above host name worked 100% fine

Unable to register user in xmpp chat app

I want to implement XMPP framework in my iOS App, I have completed all the things in (Chatting with other users , showing presence of other users , etc.)
But the problem is , I am unable to get the new user registered from my App. I am using following code for that,
if ([appDel.xmppStream supportsInBandRegistration])
[appDel.xmppStream registerWithPassword:txt_Password.text error:nil];
But for this, supportsInBandRegistration method always returns NO and I dont get called the method never registerWithPassword: .
Help me if any solution available
What server are you using? Some servers support in-band registration even thought they don't send the correct stream:feature according to XEP-0077. Most of them should give the feature in the disco results however.
---- OR ----
You can solve this by following code. It's working fine for me. :
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:
(NSXMLElement *)error;
{
NSLog(#"Did not authenticate");
[xmppStream registerWithPassword:[[NSUserDefaults
standardUserDefaults] stringForKey:#"userPassword"] error:nil];
NSError * err = nil;
if(![[self xmppStream] registerWithPassword:password error:&err])
{
NSLog(#"Error registering: %#", err);
}
}
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
NSLog(#"I'm in register method");
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement
*)error{
NSLog(#"Sorry the registration is failed");
}
I declare the registerWithPassword:error: method in
didNotAuthenticate: method because after connection to the server it
is going to this didNotAuthenticate method through where my
registration methods is working fine
I had the same problem that [xmppStream supportsInBandRegistration] method was returning false because i was passing Jid that was already registered in the server.
[xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
changes JID worked for me.

i want to store some data in "EverNote" through our app

i want to store some data in "EverNote" through our app either (image or text or both).
I googled, i got some guidance like EverNote SDK and i got the EverNoteCounter Sample also(When i run this, when i click getCount button it shows an alert message "Could not authenticate").
I generated the developer token also.
But i unable to create the consumerKey,consumerSecret. And also i did not find how to store our data to evernote from our app.
I got some links like this one
but when i go through that link it says( HTTP method GET is not supported by this URL)
I able to authenticate with the EVERNOTE and i able to get the number of notebooks in that Account.
I am using sqllite in my app. i am using one folder for images. Sqllite have the images links info.
How to store the data.
I used the following code to authenticate and to get the count
- (IBAction)retrieveUserNameAndNoteCount:(id)sender
{
// Create local reference to shared session singleton
EvernoteSession *session = [EvernoteSession sharedSession];
[session authenticateWithViewController:self completionHandler:^(NSError *error) {
// Authentication response is handled in this block
if (error || !session.isAuthenticated) {
// Either we couldn't authenticate or something else went wrong - inform the user
if (error) {
NSLog(#"Error authenticating with Evernote service: %#", error);
}
if (!session.isAuthenticated) {
NSLog(#"User could not be authenticated.");
}
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not authenticate"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[alert show];
} else {
// We're authenticated!
EvernoteUserStore *userStore = [EvernoteUserStore userStore];
// Retrieve the authenticated user as an EDAMUser instance
[userStore getUserWithSuccess:^(EDAMUser *user) {
// Set usernameField (UILabel) text value to username
[usernameField setText:[user username]];
// Retrieve total note count and display it
[self countAllNotesAndSetTextField];
} failure:^(NSError *error) {
NSLog(#"Error retrieving authenticated user: %#", error);
}];
}
}];
}
- (void)countAllNotesAndSetTextField
{
// Allow access to this variable within the block context below (using __block keyword)
__block int noteCount = 0;
EvernoteNoteStore *noteStore = [EvernoteNoteStore noteStore];
[noteStore listNotebooksWithSuccess:^(NSArray *notebooks) {
for (EDAMNotebook *notebook in notebooks) {
if ([notebook guid]) {
EDAMNoteFilter *filter = [[EDAMNoteFilter alloc] init];
[filter setNotebookGuid:[notebook guid]];
[noteStore findNoteCountsWithFilter:filter withTrash:NO success:^(EDAMNoteCollectionCounts *counts) {
if (counts) {
// Get note count for the current notebook and add it to the displayed total
NSNumber *notebookCount = (NSNumber *)[[counts notebookCounts] objectForKey:[notebook guid]];
noteCount = noteCount + [notebookCount intValue];
NSString *noteCountString = [NSString stringWithFormat:#"%d", noteCount];
[noteCountField setText:noteCountString];
}
} failure:^(NSError *error) {
NSLog(#"Error while retrieving note counts: %#", error);
}];
}
}
} failure:^(NSError *error) {
NSLog(#"Error while retrieving notebooks: %#", error);
}];
}
Please suggest me the links or give me the guidance
Thanks a lot in advance
Developer token is to be used when you only need to access your own account. To get a consumer key/secret, go here : http://dev.evernote.com/documentation/cloud/ .
If you are using iOS, https://github.com/evernote/evernote-sdk-ios has a sample app that you can use once you have a consumer key and secret.
In general, there is a lot of information on dev.evernote.com.
All SDKs are located at https://github.com/evernote
Getting started guide for iOS : http://blog.evernote.com/tech/2012/05/24/evernote-sdk-integration-ios/
Did you solved it? If not, i did the following to get it work:
download and include sdk
get consumerKey and secret (if you want to access notes too, then
instead of basic you should request for full access, http://dev.evernote.com/documentation/cloud/ top right corner)
Add the URLType entry in info.plist ("Modify your application's main
plist file" chapter https://github.com/evernote/evernote-sdk-ios)
Copy the session init code (filled with consumer key and secret, the hostname should be left unchanged) and implement the two application delegate specific code
An (on-screen) viewcontroller should be passed on authenticating the user to authenticateWithViewController method, f.e. the appdelegate's rootViewController
Study this pages to understand the model hierarchy used by Evernote:
http://dev.evernote.com/documentation/cloud/chapters/data_structure.php
http://dev.evernote.com/documentation/reference/Types.html
Image could be stored as EDAMResource (Resource) in the field data and text as EDAMNote (Note) in the field content. Both is handled by Evernote SDK's EvernoteNoteStore object.

iphone: secure restfull server "The certificate for this server is invalid

I am trying to consume secure restful service which gives error
Error = Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xxx.xxx.xxx.xxx” which could put your confidential information at risk."
working on xCode 4.2, where is the mistake or any step missing.
using following code
RegisterUser.f
#interface RegisterUser : UIViewController<UITextFieldDelegate,
UIScrollViewDelegate, NSURLConnectionDelegate>
RegisterUser.m
- (IBAction)SubmitBtnAction:(id)sender {
NSURL *url = [NSURL URLWithString:#"https://xx.xx.xx.xxx:8223/jaxrs/tunedoorgateway/getCountries"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] >0 && error == nil)
{
NSLog(#"Data = %#", data);
// DO YOUR WORK HERE
}
else if ([data length] == 0 && error == nil)
{
NSLog(#"Nothing was downloaded.");
}
else if (error != nil){
NSLog(#"Error = %#", error);
}
}];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
NSLog(#"This is canAuthenticateAgainstProtectionSpace");
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
// if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
// if ([trustedHosts containsObject:challenge.protectionSpace.host])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
NSLog(#"This is didReceiveAuthenticationChallenge");
// [[challenge sender] cancelAuthenticationChallenge:challenge];
}
I feel this might be because of DNS, something like your server is not registered.
Try using this for development:
Create an NSURLRequest+NSURLRequestSSLY.h file and add these lines to it
#import <Foundation/Foundation.h>
#interface NSURLRequest (NSURLRequestSSLY)
+(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
#end
Create an NSURLRequest+NSURLRequestSSLY.m file and add these lines to it
#import "NSURLRequest+NSURLRequestSSLY.h"
#implementation NSURLRequest (NSURLRequestSSLY)
+(BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host
{
return YES;
}
#end
And don't forget to remove it before publishing as your app might get rejected.
The failure is not in your code. You are using a HTTPS server which does not provide a known certificate. If you have setup the server yourself you have to go and buy a singed certificate from one of the big certification authorities which are trusted by iOS and most other operating systems.
For development purposes you can test your REST service by ignoring the non-trusted certificate. Follow this guide for doing that: http://www.cocoanetics.com/2009/11/ignoring-certificate-errors-on-nsurlrequest/
But for production use I recommend you do not use this method since it will bring a security leak to your application. If you do ignore security you can also just use HTTP instead of HTTPS.
I have tried several way and found out it is related with apple developer centre certificate.
Upgrade your provisioning and try it again. I have tried posting data with iPad, iPhone 5 and 5S but iPhone 4.
When I have update my provisioning and installing on my iPhone 4, works with now issue.