send message using quickblox - ios

I've integrated quickblox in my app. as I fetched all user in tableview using this code
QBGeneralResponsePage *page = [QBGeneralResponsePage responsePageWithCurrentPage:1 perPage:100];
[QBRequest usersForPage:page successBlock:^(QBResponse *response, QBGeneralResponsePage *pageInformation, NSArray *users)
{
[_NameArray addObjectsFromArray:users];
}
errorBlock:^(QBResponse *response)
{
}];
}
errorBlock:^(QBResponse *response)
{
NSLog(#"error: %#", response.error);
}];
in _nameArray I've all user information in QBUUSER object form
QBUUser *obj = [Array objectAtIndex:indexPath.row];
NSString *name = obj.fullname;
in retrieve all user. now when loginUser click on particular contact or retrieve user then i create private group one to one communication using this code
-(void)chat
{
chatDialog = [[QBChatDialog alloc] initWithDialogID:NULL type:QBChatDialogTypePrivate];
chatDialog.occupantIDs = #[#(chatuserobj.ID)];
[QBRequest createDialog:chatDialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog) {
} errorBlock:^(QBResponse *response) {
}];
}
and main thing send and receive message in that view controller i have taken textfield for sending message and table view for show message for sending message i have used this code
-(void)startChat
{
[[QBChat instance] addDelegate:self];
QBChatMessage *message = [QBChatMessage message];
[message setText:#"Hey there"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"save_to_history"] = #YES;
[message setCustomParameters:params];
[chatDialog sendMessage:message completionBlock:^(NSError * _Nullable error)
{
NSLog(#"Message sent");
}];
}
and used below delegate method
- (void)chatDidReceiveMessage:(QBChatMessage *)message
I actually see the private group in admin panel of quickblox but don't see the sent message. please help me.

Instead of you're code like:
[chatDialog sendMessage:message completionBlock:^(NSError * _Nullable error)
{
NSLog(#"Message sent");
}];
Use the following code:
[QBRequest createMessage:message successBlock:^(QBResponse *response, QBChatMessage *createdMessage) {
NSLog(#"success: %#", createdMessage);
} errorBlock:^(QBResponse *response) {
NSLog(#"ERROR: %#", response.error);
}];
I use Code like:
#pragma mark Tool bar Actions
- (void)didPressSendButton:(UIButton *)button
withMessageText:(NSString *)text
senderId:(NSUInteger)senderId
senderDisplayName:(NSString *)senderDisplayName
date:(NSDate *)date {
[[QBChat instance] addDelegate:self];
QBChatMessage *message = [QBChatMessage message];
[message setText:text];
message.senderID = senderId;
message.recipientID= [[NSUserDefaults standardUserDefaults] integerForKey:#"CurrentRecipientID"];
message.dateSent = [NSDate date];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"save_to_history"] = #YES;
[message setCustomParameters:params];
[QBRequest createMessage:message successBlock:^(QBResponse *response, QBChatMessage *createdMessage) {
NSLog(#"success: %#", createdMessage);
[self.chatSectionManager addMessage:createdMessage];
} errorBlock:^(QBResponse *response) {
NSLog(#"ERROR: %#", response.error);
}];
[self finishSendingMessageAnimated:YES];
}

Related

not getting email id with linkedin swift [duplicate]

I want to include a "Sign Up using LinkedIn" feature in my app.
I'd like to be able to get some information, such as name and email.
By default I am able to get a name, but I'm stuck on getting the email.
My results are in JSON.
Here's my code:
- (IBAction)logInWithLinkedIn:(id)sender
{
if ([_client validToken])
{
[self requestMeWithToken:[_client accessToken]];
}
else
{
[_client getAuthorizationCode:^(NSString *code)
{
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:#"access_token"];
[self requestMeWithToken:accessToken];
} failure:^(NSError *error) {
NSLog(#"Quering accessToken failed %#", error);
}];
} cancel:^{
NSLog(#"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(#"Authorization failed %#", error);
}];
}
}
- (void)requestMeWithToken:(NSString *)accessToken
{
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(#"current user %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
}];
}
- (LIALinkedInHttpClient *)client
{
LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:#"redirectURL"
clientId:#"key"
clientSecret:#"secret"
state:#"state"
grantedAccess:#[#"r_emailaddress"]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil];
}
My result is:
firstName
headline
lastName
siteStandardProfileRequest
Anyone see how I can get the email?
You should use:
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result)
This may helps :)
You can use LinkedIn SDK
+ (void)loginToLinkedInAndFetchProfileData:(RequestResult)resultHandler
{
void (^PerformDataFetch)() = ^() {
if ([LISDKSessionManager hasValidSession]) {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,maiden-name,email-address)", LINKEDIN_API_URL];
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSString *token = [[LISDKSessionManager sharedInstance].session.accessToken serializedString];
[[NSUserDefaults standardUserDefaults] setValue:token forKey:LinkedInAccessTokenKey];
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
id value = [NSJSONSerialization JSONObjectWithData:objectData options:kNilOptions error:nil];
resultHandler(value, nil);
} error:^(LISDKAPIError *error) {
resultHandler(nil, error);
}];
}
};
NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:LinkedInAccessTokenKey];
if (token.length) {
LISDKAccessToken *accessToken = [LISDKAccessToken LISDKAccessTokenWithSerializedString:token];
if ([accessToken.expiration isLaterThan:[NSDate date]]) {
[LISDKSessionManager createSessionWithAccessToken:accessToken];
PerformDataFetch();
}
} else {
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) {
PerformDataFetch();
} errorBlock:^(NSError *error) {
resultHandler(nil, error);
}];
}
}
Response
> {
> emailAddress = "someEmail#email.com";
> firstName = Name;
> id = "2342d-6Y";
> lastName = LastName;
> }
Also this link can be useful
Update for Swift 3:
// Set preferred scope.
let scope = "r_basicprofile%20r_emailaddress"
// Then
if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?format=json"
-(void)syncLinkedInWithCompetionHandler:(CompletionBlock)block{
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil]
state:#"some state"
showGoToAppStoreDialog:YES
successBlock:^(NSString *returnState) {
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"value=%# \nisvalid=%#",[session value],[session isValid] ? #"YES" : #"NO");
block(returnState, nil);
}
errorBlock:^(NSError *error) {
NSLog(#"%s %#","error called! ", [error description]);
block(nil, error);
}
];
}
-(void)getProfileDataWithCompletion:(CompletionBlock)block {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,headline,location,email-address)", LINKEDIN_API_URL];
NSLog(#"urlString = %#",urlString);
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSError *jsonError;
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"responseDict = %#",responseDict);
block(responseDict, nil);
} error:^(LISDKAPIError *error) {
NSLog(#"error = %#",error);
block(error, nil);
}];
}

What is the recommended Process for using QuickBlox in iOS Share Extension

I am using QuickBlox successfully in a a main iOS app and would like to extend the features in to a Share Extension using the cocoapod 'QuickBlox', '~> 2.7.5'. I needs to send the message in the background without opening the main application.
I am using the code below without any success to first setup sending text only.
[QBRequest logInWithUserLogin:USERNAME password:PASSWORD successBlock:^(QBResponse *response, QBUUser *user) {
if (user) {
user.login = USERNAME;
user.password = PASSWORD;
[[QBChat instance] connectWithUser:user completion:^(NSError * _Nullable error) {
QBChatDialog *chatDialog = [[QBChatDialog alloc] initWithDialogID:[settingsDict valueForKey:#"sendingID"] type:QBChatDialogTypeGroup];
QBChatMessage *messagetosend = [QBChatMessage message];
messagetosend.senderID = userQBID;
messagetosend.text = self.contentText;
messagetosend.dateSent = [NSDate dateWithTimeInterval:-12.0f sinceDate:[NSDate date]];
[chatDialog joinWithCompletionBlock:^(NSError * _Nullable error) {
[chatDialog sendMessage:messagetosend completionBlock:^(NSError * _Nullable error) {
NSLog(#"%#",[error localizedDescription]);
}];
}];
}
];
}
} errorBlock:^(QBResponse * _Nonnull response) { }];
You can send the message via REST. Sending via REST doesn't need to connect to chat and join in the dialog.
NSUInteger senderID = //Current User ID
QBChatMessage *message = [QBChatMessage message];
message.text = intent.content;
message.senderID = senderID;
message.markable = YES;
message.deliveredIDs = #[#(senderID)];
message.readIDs = #[#(senderID)];
message.dialogID = dialogID;
message.dateSent = [NSDate date];
[QBRequest sendMessage:message successBlock:^(QBResponse * _Nonnull response, QBChatMessage * _Nonnull createdMessage) {
} errorBlock:^(QBResponse * _Nonnull response) {
}];

Quickblox error: You are not connected and not authorized

I know this question has been asked multiple time but none of them solved my problem.
Error Domain=com.quickblox.chat Code=401 "Password not verified"
actually I have tried this:
- (void)viewDidLoad
{
[super viewDidLoad];
appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"bdsfbd %#",chatuserobj.fullName);
NSLog(#"Chat Id %lu",(unsigned long)chatuserobj.ID);
NSLog(#"Current User %#",[QBSession currentSession].currentUser);
QBUUser *currentUserr = [QBUUser user];
currentUserr.ID = appDelegate.loginUserId;
currentUserr.password = appDelegate.loginUserPassword;
// connect to Chat
[QBRequest logInWithUserLogin:appDelegate.loginUser password:appDelegate.loginUserPassword successBlock:^(QBResponse *response, QBUUser *user)
{
chatDialog = [[QBChatDialog alloc] initWithDialogID:NULL type:QBChatDialogTypePrivate];
chatDialog.occupantIDs = #[#(chatuserobj.ID)];
[QBRequest createDialog:chatDialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog)
{
NSLog(#"Created Dialog %#",createdDialog);
} errorBlock:^(QBResponse *response)
{
NSLog(#"Error %#",response);
}];
} errorBlock:^(QBResponse *response) {
}];
[[QBChat instance] connectWithUser:chatuserobj completion:^(NSError * _Nullable error)
{
NSLog(#"USer is Connected %#",error.description);
[self startChat];
}];
[QBSettings setKeepAliveInterval:30];
[QBSettings setAutoReconnectEnabled:YES];
}
and this
-(void)startChat
{
[[QBChat instance] addDelegate:self];
QBChatMessage *message = [QBChatMessage message];
[message setText:#"Hey there"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"save_to_history"] = #YES;
[message setCustomParameters:params];
[chatDialog sendMessage:message completionBlock:^(NSError * _Nullable error)
{
NSLog(#"Completed: %#",error.description);
}];
}
I don't know where I am wrong. So point out my mistake.
EDIT: again in did load
- (void)viewDidLoad
{
[super viewDidLoad];
// connect to Chat
[[QBChat instance] connectWithUser:currentUserr completion:^(NSError * _Nullable error)
{
NSLog(#"USer is Connected %#",error.description);
}];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self chat];
});
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self startChat];
});
}
chat is method for creating dialog for private group or one to one connection
-(void)chat
{
chatDialog = [[QBChatDialog alloc] initWithDialogID:NULL type:QBChatDialogTypePrivate];
chatDialog.occupantIDs = #[#(chatuserobj.ID)];
[QBRequest createDialog:chatDialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog) {
} errorBlock:^(QBResponse *response) {
}];
}
and start chat actual communication occur
-(void)startChat
{
[[QBChat instance] addDelegate:self];
QBChatMessage *message = [QBChatMessage message];
[message setText:#"Hey there"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[#"save_to_history"] = #YES;
[message setCustomParameters:params];
[chatDialog sendMessage:message completionBlock:^(NSError * _Nullable error)
{
NSLog(#"Completed: %#",error.description);
}];
}
now this error occur
UserInfo={NSLocalizedRecoverySuggestion = You are not connected to chat.
- (void)viewDidLoad
{
[super viewDidLoad];
// connect to Chat
[[QBChat instance] connectWithUser:currentUserr completion:^(NSError * _Nullable error)
{
NSLog(#"USer is Connected %#",error.description);
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self chat];
});
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self startChat];
});
}];
}
and same method of start chat and chat. it works well
[[QBChat instance] connectWithUser:chatuserobj completion:^(NSError * _Nullable error)
{
NSLog(#"USer is Connected %#",error.description);
}];
This method is used to connect yourself to the chat and not your opponents. Furthermore, in order to connect with this method your QBUUser instance must have valid password set as password property.
Basically you need to connect yourself to the chat and then just start creating dialogs and sending messages.

How to create private dialogue box using quickblox ios?

I am able to create group dialog box as I found this code:
chatDialog = [[QBChatDialog alloc] initWithDialogID:#"dialogueid" type:QBChatDialogTypeGroup];
chatDialog.name = #" Bob, Sam, Garry";
chatDialog.occupantIDs = #[#(1)];
[QBRequest createDialog:chatDialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog) {
} errorBlock:^(QBResponse *response) {
}];
but when I try to change type to QBChatDialogTypePrivate.
Dialog is not creating and can you please tell me what is dialog id and where to find it?
Just init your QBChatDialog with ID nil, server will set it for you and createdDialog that is returned by QBRequest will have correct dialogID.
QBChatDialog *chatDialog = [[QBChatDialog alloc] initWithDialogID:nil type:QBChatDialogTypePrivate];
chatDialog.occupantIDs = #[#(opponentID)];
[QBRequest createDialog:chatDialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog) {
NSLog(#"Created dialog: %#", createdDialog);
} errorBlock:^(QBResponse *response) {
NSLog(#"Failed to create dialog with error: %#", response.error);
}];

Getting Email Address from LinkedIn API

I want to include a "Sign Up using LinkedIn" feature in my app.
I'd like to be able to get some information, such as name and email.
By default I am able to get a name, but I'm stuck on getting the email.
My results are in JSON.
Here's my code:
- (IBAction)logInWithLinkedIn:(id)sender
{
if ([_client validToken])
{
[self requestMeWithToken:[_client accessToken]];
}
else
{
[_client getAuthorizationCode:^(NSString *code)
{
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:#"access_token"];
[self requestMeWithToken:accessToken];
} failure:^(NSError *error) {
NSLog(#"Quering accessToken failed %#", error);
}];
} cancel:^{
NSLog(#"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(#"Authorization failed %#", error);
}];
}
}
- (void)requestMeWithToken:(NSString *)accessToken
{
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(#"current user %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
}];
}
- (LIALinkedInHttpClient *)client
{
LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:#"redirectURL"
clientId:#"key"
clientSecret:#"secret"
state:#"state"
grantedAccess:#[#"r_emailaddress"]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil];
}
My result is:
firstName
headline
lastName
siteStandardProfileRequest
Anyone see how I can get the email?
You should use:
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result)
This may helps :)
You can use LinkedIn SDK
+ (void)loginToLinkedInAndFetchProfileData:(RequestResult)resultHandler
{
void (^PerformDataFetch)() = ^() {
if ([LISDKSessionManager hasValidSession]) {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,maiden-name,email-address)", LINKEDIN_API_URL];
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSString *token = [[LISDKSessionManager sharedInstance].session.accessToken serializedString];
[[NSUserDefaults standardUserDefaults] setValue:token forKey:LinkedInAccessTokenKey];
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
id value = [NSJSONSerialization JSONObjectWithData:objectData options:kNilOptions error:nil];
resultHandler(value, nil);
} error:^(LISDKAPIError *error) {
resultHandler(nil, error);
}];
}
};
NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:LinkedInAccessTokenKey];
if (token.length) {
LISDKAccessToken *accessToken = [LISDKAccessToken LISDKAccessTokenWithSerializedString:token];
if ([accessToken.expiration isLaterThan:[NSDate date]]) {
[LISDKSessionManager createSessionWithAccessToken:accessToken];
PerformDataFetch();
}
} else {
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) {
PerformDataFetch();
} errorBlock:^(NSError *error) {
resultHandler(nil, error);
}];
}
}
Response
> {
> emailAddress = "someEmail#email.com";
> firstName = Name;
> id = "2342d-6Y";
> lastName = LastName;
> }
Also this link can be useful
Update for Swift 3:
// Set preferred scope.
let scope = "r_basicprofile%20r_emailaddress"
// Then
if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?format=json"
-(void)syncLinkedInWithCompetionHandler:(CompletionBlock)block{
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil]
state:#"some state"
showGoToAppStoreDialog:YES
successBlock:^(NSString *returnState) {
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"value=%# \nisvalid=%#",[session value],[session isValid] ? #"YES" : #"NO");
block(returnState, nil);
}
errorBlock:^(NSError *error) {
NSLog(#"%s %#","error called! ", [error description]);
block(nil, error);
}
];
}
-(void)getProfileDataWithCompletion:(CompletionBlock)block {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,headline,location,email-address)", LINKEDIN_API_URL];
NSLog(#"urlString = %#",urlString);
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSError *jsonError;
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"responseDict = %#",responseDict);
block(responseDict, nil);
} error:^(LISDKAPIError *error) {
NSLog(#"error = %#",error);
block(error, nil);
}];
}

Resources