How can I use MailCore to fetch emails using the token I got from gmail? - objective-c

I am new to IOS developement.I have use oauth 2.0 for authentication and access token.now i want to fetch the emails using token in mailcore2. how can I do it.I had google lots of stuff but it does not worth it . So,Please help to solve this problem..
Thanks in advance. Here is my code.
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString *accessToken = [def objectForKey:#"sessionToken"];
NSLog(#"Access token:%#",accessToken);//token from google api authentication
session = [[MCOIMAPSession alloc] init];
session.hostname = #"imap.gmail.com";
session.port = 993;
session.authType =MCOAuthTypeXOAuth2;
session.OAuth2Token = accessToken;
session.username = emailId;
session.connectionType = MCOConnectionTypeTLS;
session.password = nil;
[session setConnectionLogger:^(void * connectionID, MCOConnectionLogType type,
NSData * data){
NSLog(#"MCOIMAPSession: [%i] %#", type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
MCOIMAPMessagesRequestKind requestKind = (MCOIMAPMessagesRequestKind (MCOIMAPMessagesRequestKindHeaders | MCOIMAPMessagesRequestKindStructure |MCOIMAPMessagesRequestKindInternalDate | MCOIMAPMessagesRequestKindHeaderSubject |MCOIMAPMessagesRequestKindFlags);
MCOIMAPFolderInfoOperation *inboxFolderInfo = [session folderInfoOperation:Folder];
[inboxFolderInfo start:^(NSError *error, MCOIMAPFolderInfo *info){
NSLog(#"INFO:%#",info);
}];
}
I got INFO:(null).correct me If i am doing wrong stuff.

Related

How to share HashTag Text with Video On Facebook in IOS?

I'm sharing the video on Facebook (Without the SLComposer) from my IOS App. it will send successfully but I want To add the HashTag Text With it. Im Trying it But It will not get add shared with the video (only video get shared ).
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
ShareContnt.hashtag = [FBSDKHashtag hashtagWithString:[NSString stringWithFormat:#"%#",#"We are #sharing this #video for the #testing of #video and the #HashTag Text"]];
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self];
Please Help me for this issues ?
100% Working
I got the ANS Of these...
//Using these code we only share can't send the text / Title or name of video...
-(void)facbookSharng
{
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self]
// write the deleate methdo for post ID..
}
}
//But for these Facebook gives another way,
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
NSData *videoData = [NSData dataWithContentsOfURL:appDelegateObj.finalVideoUrl];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3L];
[params setObject:videoData forKey:#"video_filename.MOV"];
[params setObject:#"Title for this post." forKey:#"title"];
[params setObject:#"#Description for this post." forKey:#"description"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/videos" parameters:params HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
//video posted
NSLog(#"Facebook sharing completed %#:",result);
strFbSocialPostId = [result valueForKey:#"id"];//post ID
}
}];
}

MCOIMAPIdleOperation Issue

I am totally new in IOS Development, And I am making a app using MailCore2 api.
Company has told me to use MCOIMApIdleOperation to get the emails from Gmail Server.
I have google all the way to find out solution about this but it is not worth it.
Here is detail about the Problem,
First I want to load the emails from the INBOX folder through MCOIMAPIdleOperation.Below is my code for fetching emails.
- (void)viewDidLoad{
[super viewDidLoad];
//Do any additional setup after loading the view from its nib.
//Made connection with Gmail Imap Server
NSUserDefaults *defaules = [NSUserDefaults standardUserDefaults];
NSString *emailid = [defaules objectForKey:#"emailid" ];
NSString *password = [defaules objectForKey:#"password" ];
session = [[MCOIMAPSession alloc] init];
session.hostname = #"imap.gmail.com";
session.port = 993;
session.username = emailid;
session.password = password;
session.connectionType = MCOConnectionTypeTLS;
idle=[session idleOperationWithFolder:#"INBOX" lastKnownUID:0];
[idle start:^(NSError *err){
MCOIMAPMessagesRequestKind requestKind = (MCOIMAPMessagesRequestKind)
(MCOIMAPMessagesRequestKindHeaders | MCOIMAPMessagesRequestKindStructure |MCOIMAPMessagesRequestKindInternalDate | MCOIMAPMessagesRequestKindHeaderSubject |MCOIMAPMessagesRequestKindFlags);
MCOIMAPFolderInfoOperation *inboxFolderInfo = [session folderInfoOperation:Folder];
NSLog(#"statrt1");
[inboxFolderInfo start:^(NSError *error, MCOIMAPFolderInfo *info)
{
NSLog(#"start2");
BOOL totalNumberOfMessagesDidChange =
self.totalNumberOfInboxMessages != [info messageCount];
self.totalNumberOfInboxMessages = [info messageCount];
NSUInteger numberOfMessagesToLoad =MIN(self.totalNumberOfInboxMessages, nMessages);
if (numberOfMessagesToLoad == 0)
{
self.isLoading = NO;
return;
}
// If total number of messages did not change since last fetch,
// assume nothing was deleted since our last fetch and just
// fetch what we don't have
MCORange fetchRange;
if (!totalNumberOfMessagesDidChange && msgbody.count)
{
numberOfMessagesToLoad -= msgbody.count;
fetchRange = MCORangeMake(self.totalNumberOfInboxMessages -msgbody.count -(numberOfMessagesToLoad - 1),(numberOfMessagesToLoad - 1));
}
// Else just fetch the last N messages
else
{
fetchRange =MCORangeMake(self.totalNumberOfInboxMessages -(numberOfMessagesToLoad - 1),(numberOfMessagesToLoad - 1));
}
MCOIMAPFetchMessagesOperation *imapMessagesFetchOp =[session fetchMessagesByNumberOperationWithFolder:Folder requestKind:requestKind numbers:
[MCOIndexSet indexSetWithRange:fetchRange]];
[imapMessagesFetchOp start:^(NSError *error, NSArray *messages, MCOIndexSet *vanishedMessages)
{
NSSortDescriptor *sort =[NSSortDescriptor sortDescriptorWithKey:#"header.date" ascending:NO];
NSMutableArray *combinedMessages = [NSMutableArray arrayWithArray:messages];
[combinedMessages removeAllObjects];
[combinedMessages addObjectsFromArray:messages];
msgbody=[combinedMessages sortedArrayUsingDescriptors:#[sort]];
[uitable reloadData];
}];
}];
}];
}
By Above code mails are fetched successfully.Problem is when new mail is arrive above code is not running again.what to do so that i can get the new mails when they arrive..
Please help me to solve this issue.

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?

Objective C how to get a Facebook access token

I'm having some trouble pulling a Facebook access token from the web for a Facebook Feed App I'm writing. The problem isn't strictly related to gaining a Facebook token; this just frames the problem. When I go to https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=[APP_ID]&client_secret=[APP_SECRET], I am returned a token on a page that simply says:
access_token=464483653570261|cY9NHFBWCDJ9hSQfswWFg0FDZvw
How can I parse that from the webpage into my app? I'm relatively new to Objective C (and I've only got a year of basic coding experience), so I tried to use part of a method that I found online to get a JSON feed, combined with a simple parsing method, but it didn't work. The code is as follows:
id getToken = [self objectWithUrl:[NSURL URLWithString:#"https://graph.facebook.com/
oauth/access_token?grant_type=client_credentials&
client_id=464483653570261&
client_secret=55bb8395ed0293bf37af695f6cdaa1fb"]];
NSString *fullToken = (NSString *)getToken;
NSLog(#"fullToken: %#", fullToken);
NSArray *components = [fullToken componentsSeparatedByString:#"="];
NSString *token = [components objectAtIndex:1];
NSLog(#"token: %#", token);
Both of my NSLogs say that the respective Strings point to (null). I'm not really certain what I'm doing wrong, and I haven't had much luck finding answers on the internet, as I'm not sure what to call what I'm trying to do. I'd appreciate any help, or alternate methods, that you might have.
By the look of it, the value you're getting isn't JSON, it's just a string.
Try something like this:
NSURL * url = [NSURL URLWithString:#"https://graph.facebook.com/
oauth/access_token?grant_type=client_credentials&
client_id=464483653570261&
client_secret=55bb8395ed0293bf37af695f6cdaa1fb"]];
NSString * fullToken = [NSString stringWithContentsOfUrl: url];
NSLog(#"fullToken: %#", fullToken);
NSArray *components = [fullToken componentsSeparatedByString:#"="];
NSString *token = [components objectAtIndex:1];
NSLog(#"token: %#", token);
There is a more simple way of getting User's access_token using the ACAccountStore & ACAccountType. Check the Full Code Below:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *FBOptions = [NSDictionary dictionaryWithObjectsAndKeys:FACEBOOK_APP_ID, ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[accountStore requestAccessToAccountsWithType:accountType options:FBOptions completion:
^(BOOL granted, NSError *error) {
if (granted) {
NSArray *facebookAccounts = [accountStore accountsWithAccountType:accountType];
FBAccount = [facebookAccounts firstObject];
NSLog(#"token :%#",[[FBAccount credential] oauthToken]);
} else {
NSLog(#"error getting permission %#",error);
if([error code]== ACErrorAccountNotFound){
NSLog(#"Account not found. Please setup your account in settings app");
}
else {
NSLog(#"Account access denied");
}
}
}];

Is there quick way to check user access using ALAssetsLibrary?

I think this is a really bad way to check user access to the resources.
Is there better way to get user access?
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// create library
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
accessGiven = YES;
return ;
};
void (^assetGroupEnumberatorFailure)(NSError *) = ^(NSError *error) {
accessGiven = NO;
return;
};
// create 2 blocks
NSURL *url = [[NSURL alloc] initWithString:#" "];
[library assetForURL:url resultBlock:resultblock failureBlock:assetGroupEnumberatorFailure];
// use empty url to check acces..
[library release];
iOS 6.0 has better way to do that.
[ALAssetsLibrary authorizationStatus];
Method Description
Authorization Status Enum