I'm trying to Implement chat module in my app. I am successfully done with Login and Register process from Simple Chat Demo into my app. It also returns user array of offline and online users.
Now after successfully log in I am getting below log :-
error:
2012-12-07 14:50:07.056 App[5324:790b] QBChatService/xmppStreamDidConnect
2012-12-07 14:50:08.285 App[5324:790f] QBChatService/xmppStreamDidAuthenticate
2012-12-07 14:51:08.291 App[5324:711f] QBChatService/xmppStreamDidDisconnect, error=Error Domain=GCDAsyncSocketErrorDomain Code=7 "Socket closed by remote peer" UserInfo=0xb982330 {NSLocalizedDescription=Socket closed by remote peer}
And I'm not able to receive chat messages into my app.
Any suggestions ?
Edit :-
In my app, when login is done I am sending the login request to QuickBlox API
if(loginDone)
{
NSString *userName = [_textUsername.text stringByReplacingOccurrencesOfString:#"#" withString:#"_"];
NSString *userPass = [_textPassword.text stringByReplacingOccurrencesOfString:#"#" withString:#"_"];
// Authenticate user
[QBUsers logInWithUserLogin:userName password:userPass delegate:self context:userPass];
}
#pragma mark -
#pragma mark QBActionStatusDelegate
// QuickBlox API queries delegate
-(void)completedWithResult:(Result *)result context:(void *)contextInfo
{
// QuickBlox User authentication result
if([result isKindOfClass:[QBUUserLogInResult class]])
{
// Success result
if(result.success)
{
QBUUserLogInResult *res = (QBUUserLogInResult *)result;
// save current user
[[DataManager shared] setCurrentUser: res.user];
NSLog(#"%#",res.user);
[[[DataManager shared] currentUser] setPassword:(NSString *)contextInfo];
NSLog(#"%#",res.user);
// Login to Chat
[QBChat instance].delegate = self;
[[QBChat instance] loginWithUser:[[DataManager shared] currentUser]];
// Register as subscriber for Push Notifications
[QBMessages TRegisterSubscriptionWithDelegate:nil];
// send request for getting user's filelist
PagedRequest *pagedRequest = [[PagedRequest alloc] init];
[pagedRequest setPerPage:10];
[QBContent blobsWithPagedRequest:pagedRequest delegate:self];
[pagedRequest release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Errors"
message:[result.errors description]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
alert.tag = 1;
//[alert show];
[alert release];
[HUD hide:YES];
[self AfterLoginController];
}
}
}
-(void)completedWithResult:(Result *)result
{
if([result isKindOfClass:[QBUUserLogInResult class]]) // QuickBlox User authentication result
{
// Success result
if(result.success)
{
// If we are authenticating through Twitter/Facebook - we use token as user's password for Chat module
[self completedWithResult:result context:[BaseService sharedService].token];
}
}
else if ([result isKindOfClass:[QBCBlobPagedResult class]])
{
// Success result
if(result.success){
QBCBlobPagedResult *res = (QBCBlobPagedResult *)result;
// Save user's filelist
[DataManager shared].fileList = [[res.blobs mutableCopy] autorelease];
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[app startsendPresenceTimer];
[HUD hide:YES];
[self AfterLoginController];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Errors"
message:[result.errors description]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
alert.tag = 1;
//[alert show];
[alert release];
[HUD hide:YES];
[self AfterLoginController];
}
}
Now in AppDelegate :-
- (void) startsendPresenceTimer
{
[QBChat instance].delegate = self;
// send presence
if(self.sendPresenceTimer == nil)
{
self.sendPresenceTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(sendPresence) userInfo:nil
repeats:YES];
}
if (self.requesAllUsersTimer == nil)
{
self.requesAllUsersTimer= [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(updateUsers) userInfo:nil repeats:YES];
}
[self.requesAllUsersTimer fire];
}
// send presence
- (void)sendPresence{
// presence in QuickBlox Chat
[[QBChat instance] sendPresence];
// presence in QuickBlox
[QBUsers userWithExternalID:1 delegate:nil];
}
- (void)updateUsers
{
// Retrieve all users
PagedRequest* request = [[PagedRequest alloc] init];
request.perPage = 100; // 100 users
[QBUsers usersWithPagedRequest:request delegate:self];
[request release];
}
Do you send presence periodically? It need because Chat server must knows is you online or offline.
Look at QuickBlox Chat setup guide, lines
Keep in mind that QuickBlox it's simple XMPP chat, ...
Just write single line
[NSTimer scheduledTimerWithTimeInterval:30 target:[QBChat instance] selector:#selector(sendPresence) userInfo:nil repeats:YES];
Application will send presence every 30 seconds
Related
how to invite yahoo friends .on button click yahoo login page should be open.
afer login page oen i want send invitaion to my friend .plz suggest how can i do ?
for facebook we use following code but how we can do in yahoo.
-(IBAction)InviteYourFriendsBtnClk:(id)sender
{
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just smashed friends! Can you beat it?"]
title:#"StopNSwap"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// Case B: User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
NSLog(#"Request Sent.");
}
}}
friendCache:nil];
}
The easiest way to do this would be sending an email to the person asking to follow your yahoo page.
// From within your active view controller
if([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController *mailCont = [[MFMailComposeViewController alloc] init];
mailCont.mailComposeDelegate = self;
[mailCont setSubject:#"Follow us on Yahoo!"];
[mailCont setToRecipients:[NSArray arrayWithObject:#"stkovf#jaydz49.com"]];
[mailCont setMessageBody:#"Follow our apps yahoo page" isHTML:NO];
[self presentModalViewController:mailCont animated:YES];
[mailCont release]; }
// Then implement the delegate method
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
[self dismissModalViewControllerAnimated:YES]; }
I'm new in facebook SDK and iOS deverlop, my app have a problem when user login facebook, when I use a same account fb to login, my app always show this login dialog:
I want my app only show that dialog when a fb account login in the first time, but I don't know how to do it, here is my code:
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen:
if (!error) {
mainViewController *mainView = [self.storyboard instantiateViewControllerWithIdentifier:#"mainView"];
[self.navigationController pushViewController:mainView animated:YES];
// We have a valid session
NSLog(#"User session found");
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",
#"user_likes",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (IBAction)authLogin:(id)sender {
[self openSessionWithAllowLoginUI:YES];
}
I use fb sdk 3.2 and ios simulator 6.1
I think this will help you,have a look :
Facebook developer section
Hi how can I get the number of followers of the current twitter user in iOS 6. The TWRequest is depreciated so how can I use the new Social.Framework to get the number of followers?
First, you need to Authenticate your request (Get permission).
second, see follow these steps:
1.Download FHSTwitterEngine Twitter Library.
2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".
3.add SystemConfiguration.framework to your project.
Usage : 1.in the [ViewDidLoad] add the following code:
UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logIn.frame = CGRectMake(100, 100, 100, 100);
[logIn setTitle:#"Login" forState:UIControlStateNormal];
[logIn addTarget:self action:#selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logIn];
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:#"<consumer_key>" andSecret:#"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];
and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.
you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
}];
}
when the Login window is presented, enter your Twitter Username and Password to authenticate your request.
add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[FHSTwitterEngine sharedEngine]loadAccessToken];
NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
if (username.length > 0) {
lbl.text = [NSString stringWithFormat:#"Logged in as %#",username];
[self listResults];
} else {
lbl.text = #"You are not logged in.";
}
}
- (void)storeAccessToken:(NSString *)accessToken {
[[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:#"SavedAccessHTTPBody"];
}
- (NSString *)loadAccessToken {
return [[NSUserDefaults standardUserDefaults]objectForKey:#"SavedAccessHTTPBody"];
}
4.Now you are ready to get your request, the following method will list your followers ID's, add them to an NSArray and the get the Count from the NSArray:
- (Void)listFriends:(id)sender {
NSMutableArray *arr = [[NSMutableArray alloc]init];
[_tweetField resignFirstResponder];
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// NSLog(#"Friends' IDs: %#",[[FHSTwitterEngine sharedEngine]getFriendsIDs]);
dict = [[FHSTwitterEngine sharedEngine]getFollowersIDs];
for (NSDictionary *item in [dict objectForKey:#"ids"]) {
[arr addObject:[dict objectForKey:#"ids"]];
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"====> %d",[arr count]);
}
});
}
});
}
I tested this code and it's working perfectly ^_^.
use This code
(IBAction)listFriends:(id)sender {
NSMutableArray *arr = [[NSMutableArray alloc]init];
dict=[[NSMutableDictionary alloc]init];
[_tweetField resignFirstResponder];
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//to get friends id.......
NSLog(#"Friends' IDs: %#",[[FHSTwitterEngine sharedEngine]getFriendsIDs]);
/* dict = [[FHSTwitterEngine sharedEngine]getFollowersIDs];
for (NSDictionary *item in [dict objectForKey:#"ids"]) {
[arr addObject:[dict objectForKey:#"ids"]];
}*/
// To get friends name ...
// NSLog(#"Friends_Name: %#",[[FHSTwitterEngine sharedEngine]listFriendsForUser:_loggedInUserLabel.text isID:NO withCursor:#"-1"]);
dict = [[FHSTwitterEngine sharedEngine]listFriendsForUser:_loggedInUserLabel.text isID:NO withCursor:#"-1"];
NSLog(#"====> %#",[dict objectForKey:#"users"] );
NSMutableArray *array=[dict objectForKey:#"users"];
for(int i=0;i<[array count];i++)
{
NSLog(#"names:%#",[[array objectAtIndex:i]objectForKey:#"name"]);
}
// NSLog(#"Friends_Name: %#",[[FHSTwitterEngine sharedEngine]getMentionsTimelineWithCount:1000 sinceID:nil maxID:nil]);
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// NSLog(#"====> %d",[arr count]);
}
});
}
});
}
I have used Facebook sdk 3.1 in my ios app for sharing link on friends wall. I try to open a new session in the applicationDidFinishLaunching method as below
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
myAppDelegate = self;
AudioViewController *viewController = [[AudioViewController alloc] init];
self.navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.navController setNavigationBarHidden:YES];
viewController = nil;
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
// No? Display the login page.
[self performSelector:#selector(login) withObject:nil afterDelay:0.5];
}
return YES;
}
- (void)login{
[self openSessionWithAllowLoginUI:YES];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error{
switch (state) {
case FBSessionStateOpen: {
DLOG(#"session open");
}
break;
case FBSessionStateClosed: {
DLOG(#"session closed");
[FBSession.activeSession closeAndClearTokenInformation];
}
break;
case FBSessionStateClosedLoginFailed: {
DLOG(#"session Failed");
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:WVSessionStateChangedNotification
object:session];
if (error) {
DLOG(#"error = %#",error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#",
[AppDelegate FBErrorCodeDescription:error.code]]
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
With some of the Facebook accounts it returns error "The operation could not be completed" com.facebook.sdk error 2. and so further cannot post on Facebook.
Am I doing something wrong here ?Any help would be appreciated.!
I had same issue, and i have solved it by calling openSessionWithAllowLoginUI:TRUE via NSTimer.
if (![self openSessionWithAllowLoginUI:NO]) {
// No? Display the login page.
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(login) userInfo:nil repeats:NO];
}
The reason is, we can't get FB session on different threads, either we use main thread or another(background) thread. In your code, when you check session availability, you use main thread and for login, you use different thread via performSelector function.
Hope, it will help you.
thanks
I am new to iphone development. I am building an app through which i can send the email.I am using the following code
- (IBAction)btnsendPressAction:(id)sender {
if([MFMailComposeViewController canSendMail]){
MFMailComposeViewController *mailer=[[MFMailComposeViewController alloc]init];
mailer.mailComposeDelegate=self;
[mailer setSubject:#"A Message for testing"];
NSArray *toRecipients = [NSArray arrayWithObjects:#"rajshetty2125#gmail.com", #"secondMail#example.com", nil];
[mailer setToRecipients:toRecipients];
UIImage *image=[UIImage imageNamed:#"logo.png"];
NSData *imageData=UIImagePNGRepresentation(image);
[mailer addAttachmentData:imageData mimeType:#"image/png" fileName:#"logo.png"];
NSString *emailBody=#"This is test email";
[mailer setMessageBody:emailBody isHTML:NO];
[self presentModalViewController:mailer animated:YES];
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
}
else{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"failure" message:#"Alert" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
My problem is mailComposeController delegate is not getting called and I am not able to send email through my app.I went through many links , but every where I found the same method. Can anyone help me on this ?
You won't be able to send email from Simulator. You can only check this functionality on iOS device with any account configured in Mail application.
Here use this link and your add(configured) an account in device then only you can send the mail.
This snippet is working for me:
if ([MFMailComposeViewController canSendMail]) {
self.mailController = [[MFMailComposeViewController alloc] init];
[self.mailController setSubject:#"Invitation"];
[self.mailController setMessageBody:#"Message" isHTML:NO];
self.mailController.mailComposeDelegate = self;
[self presentModalViewController:self.mailController animated:YES];
}
but make sure that you're implement delegate in interface
#interface MyClass() <MFMailComposeViewControllerDelegate>
and check your callback method:
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
}
hey i am not sure but may be it's helpful, replace your last line
mailer.modalPresentationStyle = UIModalPresentationPageSheet ;
with
[self presentModalViewController: mailer animated:YES];