How can i get latest new mail using Mailcore2 Api? - ios7

I am new bie in IOS developement.I am stuck in this problem
I am using Mailcore2 api in my ios app.I want to get the new emails which are recently coming in Inbox.
Here is my Code
In ViewDidLoad method..
-(void)viewDidLoad
{
[super viewDidLoad];
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;
MCOIMAPIdleOperation *idle=[session idleOperationWithFolder:#"INBOX" lastKnownUID:64];
[idle start:^(NSError *error)
{
NSLog(#"finished checking account.");
if (error) {
NSLog(#"ERROR-%#",error);
}
else
{
NSLog(#"DONE");
[self fetchemail:10 folder:#"INBOX"];
}
}];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[idle interruptIdle];
NSLog(#"HELOO");
});
}
by this method all the emails are loaded when the view is load.
I have use MCOIMAPIdleoperation to get latest emails but it is not working.
but latest email is not fetched.
Please Help to get over it..

Related

Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service

Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
I'm getting this message regularly in iOS when I try to load HTML in WKWebView. Also it's repeating when I open a WKWebView page.
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
_articleWebView = [[WKWebView alloc] initWithFrame:_mainView.containterViiew.bounds configuration:conf];
_articleWebView.navigationDelegate = self;
_articleWebView.scrollView.scrollEnabled = NO;
[_mainView.containterViiew addSubview:_articleWebView];
[_articleWebView loadHTMLString:_articleDesc.pageContent baseURL:nil];
Also I'm trying to get the content height of the WKWebView in finish method. When the above error occurs, I am getting different height values.
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
[webView evaluateJavaScript:#"document.readyState"
completionHandler:^(id complete, NSError * _Nullable error) {
if (complete != nil) {
NSString *javascriptString = #"var body = document.body;var html = document.documentElement;Math.max(html.offsetHeight);";
[webView evaluateJavaScript:javascriptString
completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (!error) {
NSNumber *height = result;
NSLog(#"height ----------->>>%#", height);
});
}
}];
}

chatDidReceiveMessage method not called QuickBlox

I am using QuickBlox-iOS SDK for chatting. Login/Signup is working perfectly. Also I am able to send message but the delegate method
- (void)chatDidReceiveMessage:(QBChatMessage *)message;
is not getting called. Here's the code I am using to setup chat. Adding the following code in appDelegate :
// connect to Chat
[[QBChat instance] addDelegate:self];
QBUUser *currentUser = [QBUUser user];
currentUser.ID = [Global sharedInstance].currentUser.ID;
currentUser.password = #"password";
[[QBChat instance] connectWithUser:currentUser completion:^(NSError * _Nullable error) {
NSLog(#"connect to chat error %#",error);
}];
And the below code I am using to send message :
QBChatMessage *message = [QBChatMessage message];
message.recipientID=[Global sharedInstance].QBUserID;
message.senderID=[Global sharedInstance].currentUser.ID;
[message setText:messageTextView.text];
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);
} errorBlock:^(QBResponse *response) {
NSLog(#"ERROR: %#", response.error);
}]
I checked on QuickBlox dashboard. It shows all the sent/received messages. But the delegate is not getting called when I send message to another user. I am not using any additional services classes (QMServices) like they are using in their Example Project. Any help would be appreciated. Thanks
I don't understand why you're using the [QBRequest createMessage:successBlock:errorBlock:] method to send messages to another user.
For me what always worked was to create a chatDialog with the user you're trying to message, like so:
QBChatDialog *dialog = [[QBChatDialog alloc] initWithDialogID:nil
type: QBChatDialogTypePrivate];
dialog.occupantIDs = #[#([Global instance].QBUserID),
#([Global instance].currentUser.user.ID)];
Afterwards, you can call Quickblox method to create the dialog on the servers:
if (dialog.ID == nil) {
[QBRequest createDialog:dialog successBlock:^(QBResponse *response, QBChatDialog *createdDialog) {
[self sendMessageToDialog: dialog withText:#"Hello friend!"];
} errorBlock:^(QBResponse *response) {
NSLog(#"dialog creation err: %#", response);
}];
}
Create the message:
- (QBChatMessage *) createMessageWithText: (NSString *)text andDialog: (QBChatDialog*)dialog {
QBChatMessage *message = [QBChatMessage message];
message.text = text;
message.senderID = [Global instance].currentUser.ID;
message.markable = YES;
message.deliveredIDs = #[#([Global instance].currentUser.ID)];
message.readIDs = #[#([Global instance].currentUser.ID)];
message.dialogID = dialog.ID;
message.dateSent = [NSDate date];
message.recipientID = dialog.recipientID;
message.customParameters = [NSMutableDictionary dictionary];
message.customParameters[kQMCustomParameterDialogID] = dialog.ID;
message.customParameters[kQMCustomParameterDialogType] = [NSString stringWithFormat:#"%lu",(unsigned long)dialog.type];
message.customParameters[#"application_id"] = #"<your-application-id>";
message.customParameters[#"save_to_history"] = #"1";
if (dialog.lastMessageDate != nil){
NSNumber *lastMessageDate = #((NSUInteger)[dialog.lastMessageDate timeIntervalSince1970]);
message.customParameters[kQMCustomParameterDialogRoomLastMessageDate] = [lastMessageDate stringValue];
}
if (dialog.updatedAt != nil) {
NSNumber *updatedAt = #((NSUInteger)[dialog.updatedAt timeIntervalSince1970]);
message.customParameters[kQMCustomParameterDialogRoomUpdatedDate] = [updatedAt stringValue];
}
return message;
}
And then send the message to the dialog:
- (void) sendMessageToDialog: (QBChatDialog *)dialog withText: (NSString *)text {
QBChatMessage *message = [[ChatService shared] createMessageWithText:text andDialog:self.dialog];
[dialog sendMessage:message completionBlock:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"error creating message %#", error);
} else {
NSLog(#"message sent!");
}
}];
}
I think following this flux you'll be able to receive the callback through the delegate.
EDIT - I forgot to mention the consts I used in the code above are:
NSString const *kQMCustomParameterDialogID = #"dialog_id";
NSString const *kQMCustomParameterDialogRoomName = #"room_name";
NSString const *kQMCustomParameterDialogRoomPhoto = #"room_photo";
NSString const *kQMCustomParameterDialogRoomLastMessageDate = #"room_last_message_date";
NSString const *kQMCustomParameterDialogUpdatedDate = #"dialog_updated_date";
NSString const *kQMCustomParameterDialogType = #"type";
NSString const *kQMCustomParameterDialogRoomUpdatedDate = #"room_updated_date";
Have you added <QBChatDelegate> into your .h file.

make 3 "for" loops wait for async answer. obj-c ios

I'm working on an app for iPad iOS 8, and I need to make my app wait for an answer from:
[directions calculateETAWithCompletionHandler:^(MKETAResponse *response, NSError *error) {}]
This method is inside 3 loops. I tried dispatch_semaphore_t, but the app can't continue after this line:
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
and gets stuck. I tried with dispatch_group_t and got the same result.
I guess that I'm doing something wrong, but I don't know what. I tried to search SO for similar problems and but found nothing. Can someone explain how I could accomplish this?
-(void)setTimesMissions {
for (Driver *d in self.dataList) {
for (Period *p in d.periods) {
for (Mission *m in p.missions) {
MKDirections *directions = ....
// HERE i want the for loop stop until this completionHandler finish
[directions calculateETAWithCompletionHandler:^(MKETAResponse *response, NSError *error) {
//and when he finish here continue
}];
}
}
}
}
Call your method in dispatch_async block.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[youClassInstance setTimesMissions];
});
And use dispatch_semaphore_wait in your loop
- (void)setTimesMissions {
Mission *home = [[Mission alloc]init];
Mission *next = [[Mission alloc]init];
for (Driver *d in self.dataList) {
home.clientLat = d.centralPointLat;
home.clientLon = d.centralPointLon;
home.clientPaddres = d.centralAddress;
for (Period *p in d.periods) {
home.times = [[NSMutableArray alloc]init];
if ([p.periodIx isEqualToString:self.thisPeriodIX]) {
for (Mission *m in p.missions) {
Mission *source = home;
Mission *destination = m ;
MKPlacemark *placemarkSource = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake([source.clientLat doubleValue], [source.clientLon doubleValue]) addressDictionary:nil] ;
MKMapItem *mapItemSource = [[MKMapItem alloc] initWithPlacemark:placemarkSource];
MKPlacemark *placemarkDestination = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake([destination.clientLat doubleValue], [destination.clientLon doubleValue])addressDictionary:nil] ;
MKMapItem *mapItemDestination = [[MKMapItem alloc] initWithPlacemark:placemarkDestination];
MKDirectionsRequest *directionsRequest = [[MKDirectionsRequest alloc] init];
[directionsRequest setSource:mapItemSource];
[directionsRequest setDestination:mapItemDestination];
directionsRequest.transportType = MKDirectionsTransportTypeAutomobile;
[directionsRequest setRequestsAlternateRoutes:NO];
MKDirections *directions = [[MKDirections alloc] initWithRequest:directionsRequest];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block double timeTo;
[directions calculateETAWithCompletionHandler:^(MKETAResponse *response, NSError *error) {
if ( response.expectedTravelTime) {
timeTo = response.expectedTravelTime;
double ans = timeTo;
Time *t = [[Time alloc]init];
t.ix = m.serviceIX;
t.time = ans;
[home.times addObject:t];
}
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
dispatch_async(dispatch_get_main_queue(), ^{
// code that should be executed on main queue
});
if (next.clientPaddres) {
home = next;
}
}
}
}
}

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.

Handling duplicate selects in NSTokenField

How do I prevent duplicate select from an Array in an NSTokenField. I've implemented the delegate completionsForSubstring.
I was able to remove any duplicates with this approach, which admittedly is a little hacky but it works:
// Be sure to set the delegate of your NSTokenfield either in IB or in code.
#pragma mark - NSTokenFieldDelegate
-(NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index{
double delayInSeconds = .1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSArray *aray = [tokenField objectValue];
NSOrderedSet *set = [NSOrderedSet orderedSetWithArray:aray];
aray = [set array];
[tokenField setObjectValue:aray];
});
return tokens;
}
The best method I would say is to implement the delegate shouldAddObjects. Write the following code in the delegate.
NSString *newVal = [[tokens objectAtIndex:0] description];
NSArray *aray = [tokenField objectValue];
for (NSString * token in aray) {
#try{
if ([token isEqual:newVal]){
return nil;
}
}
#catch (NSException *exception) {
;
}
}