I am using iCloud for sqlite database sync between multiple devices.
i have implemented this functionality in my app for sqlite sync.
But data is updating after 5 mins on other devices.
is this problem from iCloud side because as far as i know we cannot manually update iCloud.
i know it is not correct to use sqlite for icloud sync but i have more 100 tables and i cannot migrate to core data.
Please find my code below:
AppDelegate.m
[self checkForiCloudAccess];
[[sqlmessenger shared] fireQueryForCloudData];
Check for iCloud Access
-(void)checkForiCloudAccess{
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(#"iCloud access at %#", ubiq);
isCloudAccees= TRUE;
}
else {
isCloudAccees= FALSE;
UIAlertView *alertb = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No iCloud acces" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertb show];
}
}
sqlmessenger.m
Fire Query to get iCloud Data
- (void)fireQueryForCloudData{
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
[query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"%K ENDSWITH '.xml'", NSMetadataItemFSNameKey];
[query setPredicate:pred];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(queryDidFinishGathering:) name:NSMetadataQueryDidFinishGatheringNotification object:query];
[query startQuery];
}
- (void)queryDidFinishGathering:(NSNotification *)notification {
NSMetadataQuery *que = [[NSMetadataQuery alloc]init];
que = [notification object];
[que disableUpdates];
[que stopQuery];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSMetadataQueryDidFinishGatheringNotification
object:que];
self.metaQuery = que;
que = nil;
UIAlertView *alrView = [[UIAlertView alloc]initWithTitle:#"" message:#"Cloud updated" delegate:Nil cancelButtonTitle:#"OK" otherButtonTitles:Nil, nil];
[alrView show];
//TODO: Comment this stupid method
//[self fetcLargeTableFromCloud];
}
Update database using Metadata query object
- (void)loadData:(NSString *)tableName {
_TblName = tableName;
for (NSMetadataItem *item in [self.metaQuery results])
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
if([filename isEqualToString:tableName])
{
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
//Conflict resolve
//[fileVersion replaceItemAtURL:url options:0 error:nil];
NSData *file = [NSData dataWithContentsOfURL:url];
[NSFileVersion removeOtherVersionsOfItemAtURL:url error:nil];
NSArray *conflicts = [NSFileVersion unresolvedConflictVersionsOfItemAtURL:url];
for (NSFileVersion *conflict in conflicts)
{
conflict.resolved = YES;
NSLog(#"conflict %#",conflict);
}
if (file) {
_arrCloudData = [[NSMutableArray alloc]init];
_tmpDict = [[NSMutableDictionary alloc]init];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:file];
[parser setDelegate:self];
[parser parse];
if (_arrCloudData.count !=0) {
[self deleteTable:tableName];
_arrColumnList = [self getColumnsForTable:tableName];
//[_arrColumnList removeObjectAtIndex:3];
// [_arrColumnList removeObjectAtIndex:5];
// [_arrColumnList removeObjectAtIndex:8];
NSString *columnNames = [_arrColumnList componentsJoinedByString:#","];
/*
NSMutableArray *arrtmp = [NSMutableArray arrayWithArray:_arrColumnList];
for (int i = 0; i<[arrtmp count]; i++) {
[arrtmp replaceObjectAtIndex:i withObject:#"?"];
}*/
// NSString *blidString = [arrtmp componentsJoinedByString:#","];
//TODO: Uncomment this lines
//NSString *query = [NSString stringWithFormat:#"Insert into %# (%#) values (%#)",tableName,columnNames,blidString];
//TODO: comment this line
NSString *query = [NSString stringWithFormat:#"Insert into %# (%#) values",tableName,columnNames];
// NSDate *parseFinish = [NSDate date];
//[self insertRowIntblMealDetails:tableName :query];
int exCount = _arrCloudData.count/500;
for (int i=0; i<=exCount; i++) {
if ([tableName isEqualToString:#"tblRecipeSubtypes"]) {
[self insertRowIntblMealDetails:tableName :query:i];
}
else{
[self insertRowIntbl:tableName :query :i];
}
}
/*
for (int i=0; i<[_arrCloudData count]; i++) {
//Genralized method
//[self insertRowInTableName:tableName:i:query];
//
//[self insertRowIntblMealDetails:tableName :i :query];
[self insertRowIntblMealDetails:tableName :query];
}*/
sqlite3_close(database);
/*
NSDate *Complete = [NSDate date];
NSTimeInterval PraseComplete = [parseFinish timeIntervalSinceDate:start];
NSTimeInterval LoopTime = [Complete timeIntervalSinceDate:parseFinish];
NSTimeInterval totalTime = [Complete timeIntervalSinceDate:start];
NSLog(#"Parse Execution Time: %f", PraseComplete);
NSLog(#"Loop Execution Time: %f", LoopTime);
NSLog(#"Total Execution Time: %# %f ",tableName, totalTime);
*/
}
else{
NSLog(#"Empty Array %#",tableName);
}
}
else{
NSLog(#"Blank File %#",tableName);
}
}
}
}
i call loaddata from respective classes to update database.
is there anyway with that i can update data early/fast or is there any problem in my code?
Thanks in Advance
Related
Requirement:
We are able to make connection from host device to multiple slave devices. For example, if device A initiate connection to device B and C, the contributor devices can accept peer connection and connected to device A. Here A is master device and B and C are contributors device. Now if B share their songs to A, A can play songs and see songs information. In meantime C will be idle but should connected. When B will finish to play songs, then C can also able to share their songs to device A.
Here are the problem that we have faced to achieve above tasks:
1. As soon as B started sharing songs to A, C got crashed. But A still able to play song shared by B.
array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]] toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
NSLog(#"localizedDescription %#",error);
To overcome from this problem directly pass array without index here toPeers:array. It is working and we are able to share and play songs with device A, but song information not receive to device A.
Here are full code that we are using:
contributor Controller :
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissViewControllerAnimated:YES completion:nil];
someMutableArray = [mediaItemCollection items];
counter = 0;
if(someMutableArray.count>1){
BOOL isselectsongone=YES;
[[NSUserDefaults standardUserDefaults] setBool:isselectsongone forKey:#"isselectsongone"];
}
[self showSpinner];
[self someSelector:nil];
}
- (void)someSelector:(NSNotification *)notification {
if(notification && someMutableArray.count>1 && counter <someMutableArray.count-1){
NSDate *start = [NSDate date];
counter=counter+1;
[self.outputStreamer stop];
self.outputStreamer = nil;
self.outputStream = nil;
}
song=[someMutableArray objectAtIndex:counter];
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info=[[NSMutableDictionary alloc] init];
info[#"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : #"";
//NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int fullminutes = floor([timeinterval floatValue] / 60); // fullminutes is an int
int fullseconds = trunc([duration floatValue] - fullminutes * 60); // fullseconds is an int
[NSTimer scheduledTimerWithTimeInterval:[duration doubleValue]target:self selector:#selector(getdata) userInfo:nil repeats:YES];
}
-(void)getdata {
NSMutableDictionary *info = [NSMutableDictionary dictionary];
info=[[NSMutableDictionary alloc] init];
info[#"title"] = [song valueForProperty:MPMediaItemPropertyTitle] ? [song valueForProperty:MPMediaItemPropertyTitle] : #"";
info[#"artist"] = [song valueForProperty:MPMediaItemPropertyArtist] ? [song valueForProperty:MPMediaItemPropertyArtist] : #"";
NSNumber *duration=[song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int fullminutes = floor([duration floatValue] / 60); // fullminutes is an int
int fullseconds = trunc([duration floatValue] - fullminutes * 60); // fullseconds is an int
info[#"duration"] = [NSString stringWithFormat:#"%d:%d", fullminutes, fullseconds];
MPMediaItemArtwork *artwork = [song valueForProperty:MPMediaItemPropertyArtwork];
UIImage *image = [artwork imageWithSize:CGSizeMake(150, 150)];
NSData * data = UIImageJPEGRepresentation(image, 0.0);
image = [UIImage imageWithData:data];
array = [[NSMutableArray alloc] initWithObjects:[self.session connectedPeers], nil];
MCPeerID* peerID11 = self.session.myPeerID;
NSMutableArray *arr=[[NSMutableArray alloc] initWithObjects:peerID11, nil];
NSLog(#"%#",arr);
if (image)
self.songArtWorkImageView.image = image;
else
self.songArtWorkImageView.image = nil;
self.songTitleLbl.text = [NSString stringWithFormat:#"%# \n[Artist : %#]", info[#"title"], info[#"artist"]];
NSError *error;
[_session sendData:[NSKeyedArchiver archivedDataWithRootObject:[info mutableCopy]] toPeers:[array objectAtIndex:0] withMode:MCSessionSendDataUnreliable error: &error];
NSLog(#"localizedDescription %#",error);
#try {
if(_session && _session.connectedPeers && [_session.connectedPeers count] > 0) {
NSLog(#"%#",[song valueForProperty:MPMediaItemPropertyAssetURL]);
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[song valueForProperty:MPMediaItemPropertyAssetURL] options:nil];
[self convertAsset: asset complition:^(BOOL Success, NSString *filePath) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if(Success) {
if(image) {
[self saveImage: image withComplition:^(BOOL status, NSString *imageName, NSURL *imageURL) {
if(status) {
#try {
[_session sendResourceAtURL:imageURL withName:imageName toPeer:[_session.connectedPeers objectAtIndex:0]withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(#"Failed to send picture to %#", error.localizedDescription);
return;
}
//Clean up the temp file
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtURL:imageURL error:nil];
}];
}
#catch (NSException *exception) {
}
}
}];
}
#try {
[self hideSpinner];
if(!self.outputStream) {
NSArray * connnectedPeers = [_session connectedPeers];
if([connnectedPeers count] != 0) {
[self outputStreamForPeer:[_session.connectedPeers objectAtIndex:0]];
}
}
}
#catch (NSException *exception) {
}
if(self.outputStream) {
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
//
[self.outputStreamer initStream:filePath];
NSLog(#"%#",filePath);
if(self.outputStreamer) {
[self.outputStreamer start];
}
else{
NSLog(#"Error: output streamer not found");
}
}
else{
//self.outputStream=[[NSOutputStream alloc] init];
self.outputStreamer = [[TDAudioOutputStreamer alloc] initWithOutputStream:self.outputStream];
[self.outputStreamer initStream:filePath];
NSLog(#"%#",filePath);
if(self.outputStreamer) {
[self.outputStreamer start];
}
}
}
else {
[UIView showMessageWithTitle:#"Error!" message:#"Error occured!" showInterval:1.5];
}
});
}];
// }
}
}
#catch (NSException *exception) {
NSLog(#"Expection: %#", [exception debugDescription]);
}
//}
}
HostViewcontroller :
- (void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
NSLog(#"%#",peerID);
NSLog(#"sessions%#",session);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
#try {
// NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:data];
info = [NSKeyedUnarchiver unarchiveObjectWithData:data];
self.songTitleLbl.text = [NSString stringWithFormat:#"%# \n[Duration: %#] [Artist : %#] ", info[#"title"], info[#"duration"], info[#"artist"]];
NSLog(#"eeret%#",self.songTitleLbl.text);
self.songArtWorkImageView.image = nil;
[self showSpinner];
}
#catch (NSException *exception) {
self.songTitleLbl.text = #"Some error occured...\nPlease try again";
self.songArtWorkImageView.image = nil;
}
});
}
Please let us know if I have missed anything here or the better way to achieve the above requirement. Any help really appreciated.
Here is a function of progressbar. In the sdk v1 I can use "S3Objectsummary" to know the summary of the the file, but in the sdk v2 i can not found the "S3Objectsummary".
Which one is the similar one in the v2? If any one can show an example that will be great.
Also, i have the same question with
S3GetObjectRequest/S3GetObjectResponse/S3PutObjectRequest/AmazonClientException
Code is in the sdk ios v1:
-(AmazonS3Client *)s3{
[self validateCredentials];
return s3;}
-(void)validateCredentials{
NSLog(#"validating credentials.");
if (s3 == nil) {
[self clearCredentials];
s3 = [[AmazonS3Client alloc] initWithAccessKey:ACCESS_KEY_ID withSecretKey:SECRET_KEY];
}
}
-(void)setProgressBar{
[delegate setProgressStatus:progPercent];
}
-(void)downloadPlists{
#try {
NSArray *Plists = [[self s3] listObjectsInBucket:#"~~~~"];
float numfile = 1;
float totalfiles = [Plists count];
for (S3ObjectSummary *file in Plists) {
float percent = numfile/totalfiles;
progPercent = [NSNumber numberWithFloat:percent];
[self performSelectorOnMainThread:#selector(setProgressBar) withObject:progPercent waitUntilDone:YES];
numfile++;
NSString *key = [file key];
NSLog(#"key: %#", key);
if ([key rangeOfString:#".plist"].location != NSNotFound) {
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistFilePath = [NSString stringWithFormat:#"%#/Plists/%#",docDir, key];
NSLog(#"plistFilePath: %#", plistFilePath);
S3GetObjectRequest *plist = [[S3GetObjectRequest alloc] initWithKey:key withBucket:#"~~~~~"];
S3GetObjectResponse *getObjectResponse = [[self s3] getObject:plist];
NSData *data2 = [NSData dataWithData: getObjectResponse.body];
NSString *courseFilePath = [plistFilePath substringToIndex:[plistFilePath rangeOfString:#"/" options:NSBackwardsSearch].location];
bool testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: courseFilePath
withIntermediateDirectories: YES
attributes: nil
error: NULL];
if (!testDirectoryCreated)
NSLog(#"error creating test directory.");
if (![data2 writeToFile:plistFilePath atomically:YES])
NSLog(#"error writing to path.");
}
}
}
#catch (NSException *exception) {
UIAlertView *failureAlert = [[UIAlertView alloc] initWithTitle:#"Oops!" message:[NSString stringWithFormat: #"There was an error performing this operation. Please try again later. Error: %#", exception] delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles: nil];
[failureAlert show];
}
}
I try to do the same thing in v2 in the code as follow, is the code right?
-(void)downloadPlists
{
AWSS3 *s3 = [AWSS3 defaultS3];
AWSS3ListObjectsRequest *listObjectReq=[AWSS3ListObjectsRequest new];
listObjectReq.bucket=#"PLists";
[[[s3 listObjects:listObjectReq] continueWithBlock:^id(BFTask *task) {
if(task.error){
NSLog(#"the request failed. error %#",task.error);
}
if(task.result){
AWSS3ListObjectsOutput *listObjectsOutput=task.result;
NSArray *Plists = task.result; //Is the result of task in listObjectOutput a NSArray?
float numfile = 1;
float totalfiles = [Plists count];
for(AWSS3Object *file in listObjectsOutput.contents){
float percent = numfile/totalfiles;
progPercent = [NSNumber numberWithFloat:percent];
[self performSelectorOnMainThread:#selector(setProgressBar) withObject:progPercent waitUntilDone:YES];
numfile++;
NSString *key = [file key];
NSLog(#"key: %#", key);
if ([key rangeOfString:#".plist"].location != NSNotFound) {
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistFilePath = [NSString stringWithFormat:#"%#/Plists/%#",docDir, key];
NSLog(#"plistFilePath: %#", plistFilePath);
AWSS3TransferManager *transferManager = [AWSS3TransferManager defaultS3TransferManager];
AWSS3TransferManagerDownloadRequest *downloadRequest = [AWSS3TransferManagerDownloadRequest new];
downloadRequest.bucket = #"PLists";
downloadRequest.key = key;
//downloadRequest.downloadingFileURL=[NSURL fileURLWithPath: #"???"]; I'm not sure the path. In sdk V1 there is no URL ?
[[transferManager download: downloadRequest] continueWithBlock:^id(BFTask *task) {
if (task.error) {
UIAlertView *failureAlert = [[UIAlertView alloc] initWithTitle:#"Oops!"
message:[NSString stringWithFormat: #"There was an error performing this operation. Please try again later. Error: %#", task.error]
delegate:nil
cancelButtonTitle:#"Okay"
otherButtonTitles: nil];
[failureAlert show];
}
if (task.result) {
AWSS3TransferManagerDownloadOutput *downloadOutput = task.result;
NSData *data2 = [NSData dataWithData: downloadOutput.body];
NSString *courseFilePath = [plistFilePath substringToIndex:[plistFilePath rangeOfString:#"/" options:NSBackwardsSearch].location];
bool testDirectoryCreated = [[NSFileManager defaultManager]createDirectoryAtPath: courseFilePath
withIntermediateDirectories: YES
attributes: nil
error: NULL];
if (!testDirectoryCreated)
NSLog(#"error creating test directory.");
if (![data2 writeToFile:plistFilePath atomically:YES])
NSLog(#"error writing to path.");
}
return nil;
}];
}
}
return nil;
}
return nil;
}] waitUntilFinished]; //In the integration test still use the "waitUntilFinisher".But in the "Working with BFTask" said the continueWithBolck won't execute until the previous asychronous call has already finished exceuting?
}
AWSS3Object in v2 is equivalent to S3ObjectSummary in v1.
You are not invoking - listObjects:, so your v2 code snippet does not work. You should take a look at the integration test as an example. Note that you should avoid calling - waitUntilFinished in your production app. See Working with BFTask for further details.
Hi i'm successfully loged in google plus. Now i'm trying to fetch friends details like emails, image, name.But getting error.
Please any one could help me, where i'm making mistake -
I tried this code -
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error {
self.plusService.authorizer = auth;
NSLog(#"%#",[NSString stringWithFormat:#"Email---> %#\n\n",[GPPSignIn sharedInstance].authentication.userEmail]);
NSLog(#"Received error %# and auth object ---> %#\n\n",error, auth);
// 1. Create a |GTLServicePlus| instance to send a request to Google+.
GTLServicePlus* plusService = [[GTLServicePlus alloc] init] ;
plusService.retryEnabled = YES;
// 2. Set a valid |GTMOAuth2Authentication| object as the authori zer.
[plusService setAuthorizer:[GPPSignIn sharedInstance].authentication];
// 3. Use the "v1" version of the Google+ API.*
plusService.apiVersion = #"v1";
GTLQueryPlus *query = [GTLQueryPlus queryForPeopleListWithUserId:#"me" collection:kGTLPlusCollectionVisible];
[plusService executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *person,
NSError *error) {
if (error)
{
GTMLoggerError(#"Error: %#", error);
}
else {
NSArray *peopleList = person.items;
NSLog(#"--People_List--->%#",peopleList);
}}];
}
Getting Error -
[lvl=3] __41-[ViewController finishedWithAuth:error:]_block_invoke() Error: Error Domain=com.google.GTLJSONRPCErrorDomain Code=401 "The operation couldn’t be completed. (Invalid Credentials)" UserInfo=0x7b0a1d10 {error=Invalid Credentials, GTLStructuredError=GTLErrorObject 0x7b089360: {message:"Invalid Credentials" code:401 data:[1]}, NSLocalizedFailureReason=(Invalid Credentials)}
for Fetching Friends Details you can use Google Contacts api
in that use
#import "GDataFeedContact.h"
#import "GDataContacts.h"
class file
then use this code to get data
-(void)getGoogleContacts
{
GDataServiceGoogleContact *service = [self contactService];
GDataServiceTicket *ticket;
BOOL shouldShowDeleted = TRUE;
const int kBuncha = 2000;
NSURL *feedURL = [GDataServiceGoogleContact contactFeedURLForUserID:kGDataServiceDefaultUser];
GDataQueryContact *query = [GDataQueryContact contactQueryWithFeedURL:feedURL];
[query setShouldShowDeleted:shouldShowDeleted];
[query setMaxResults:kBuncha];
ticket = [service fetchFeedWithQuery:query
delegate:self
didFinishSelector:#selector(contactsFetchTicket:finishedWithFeed:error:)];
[self setContactFetchTicket:ticket];
}
- (void)setContactFetchTicket:(GDataServiceTicket *)ticket
{
mContactFetchTicket = ticket;
}
- (GDataServiceGoogleContact *)contactService
{
static GDataServiceGoogleContact* service = nil;
if (!service) {
service = [[GDataServiceGoogleContact alloc] init];
[service setShouldCacheResponseData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
//pass the useremail and password.here
NSString *username = #"youremai#gmail";
NSString *password = #"yourpassword";
[service setUserCredentialsWithUsername:username
password:password];
return service;
}
- (void)contactsFetchTicket:(GDataServiceTicket *)ticket
finishedWithFeed:(GDataFeedContact *)feed
error:(NSError *)error {
if (error) {
NSDictionary *userInfo = [error userInfo];
NSLog(#"Contacts Fetch error :%#", [userInfo objectForKey:#"Error"]);
if ([[userInfo objectForKey:#"Error"] isEqual:#"BadAuthentication"]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Authentication Failed"
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
} else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Failed to get Contacts."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView show];
}
} else {
NSArray *contacts = [feed entries];
NSLog(#"Contacts Count: %d ", [contacts count]);
[googleContacts removeAllObjects];
for (int i = 0; i < [contacts count]; i++) {
GDataEntryContact *contact = [contacts objectAtIndex:i];
// Name
NSString *ContactName = [[[contact name] fullName] contentStringValue];
NSLog(#"Name : %#", ContactName);
// Email
GDataEmail *email = [[contact emailAddresses] objectAtIndex:0];
NSString *ContactEmail = #"";
if (email && [email address]) {
ContactEmail = [email address];
NSLog(#"EmailID : %#", ContactEmail);
}
// Phone
GDataPhoneNumber *phone = [[contact phoneNumbers] objectAtIndex:0];
NSString *ContactPhone = #"";
if (phone && [phone contentStringValue]) {
ContactPhone = [phone contentStringValue];
NSLog(#"Phone : %#", ContactPhone);
}
// Address
GDataStructuredPostalAddress *postalAddress = [[contact structuredPostalAddresses] objectAtIndex:0];
NSString *address = #"";
if (postalAddress) {
NSLog(#"formattedAddress : %#", [postalAddress formattedAddress]);
address = [postalAddress formattedAddress];
}
// Birthday
NSString *dob = #"";
if ([contact birthday]) {
dob = [contact birthday];
NSLog(#"dob : %#", dob);
}
if (!ContactName || !(ContactEmail || ContactPhone) ) {
NSLog(#"Empty Contact Fields. Not Adding.");
}
else
{
if (!ContactEmail ) {
ContactEmail = #"";
}
if (!ContactPhone ) {
ContactPhone = #"";
}
NSArray *keys = [[NSArray alloc] initWithObjects:#"name", #"emailId", #"phoneNumber", #"address", #"dob", nil];
NSArray *objs = [[NSArray alloc] initWithObjects:ContactName, ContactEmail, ContactPhone, address, dob, nil];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:objs forKeys:keys];
[googleContacts addObject:dict];
}
}
NSSortDescriptor *descriptor =
[[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
[googleContacts sortUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];
get the more info refer this http://dipinkrishna.com/blog/2013/07/ios-google-contacts/4/
I am working on IOS application.Integrated Dropbox successfully and saving data as record in datastores in DropBox as well.It was fine till here.But I am unable to get data after deleting application and reinstalling it.But in one scenario I am getting data i.e,"I inserted a record in any one of the tables in datastores,after inserting that when I am trying to get data Its coming successfully".But I need to get for the first time as the app installs.If any one worked on it please help me.Thanks in advance.
-(void)dropBoxScuccessLogin:(NSString *)successString
{
if ([successString isEqualToString:#"scuccess"])
{
//appdelegate.window.rootViewController = appdelegate.splitview;
NSArray *array1=[appdelegate.datastoreManager listDatastores:nil];
NSLog(#"array is %#",array1);
if (self.account)
{
NSDate *mydate=[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM-DD-yyyy hh:mm:ss a"];
NSString *stringFromDate = [formatter stringFromDate:mydate];
DBTable *customerTbl = [self.store getTable:#"DataSyncedOndate"];
DBRecord *task = [customerTbl insert:#{ #"SyncedDate": stringFromDate} ];
__weak DropBoxViewController *slf = self;
[self.store addObserver:self block:^ {
if (slf.store.status & (DBDatastoreIncoming | DBDatastoreOutgoing))
{
[self syncTasks];
}
}];
[self.store sync:nil];
}
}
else
{
NSLog(#"Dropbox Login faild");
}
}
- (void)syncTasks
{
NSLog(#"Self Account is in syncTasks is %#",self.account);
if (self.account)
{
NSDictionary *changed = [self.store sync:nil];
NSLog(#" Data is Synced");
// [self getDataSync];
dispatch_async(dispatch_get_main_queue(), ^{
[self retriveDataFromDB];
});
// [self performSelector:#selector(getDataSync) withObject:nil afterDelay:2.0];
}
else
{
// [alertView show];
}
}
in retriveDataFromDB method
-(void)retriveDataFromDB
{
NSLog(#"retrive from DB method called");
///////////Admin details///////////
NSMutableArray *tasks = [NSMutableArray arrayWithArray:[[self.store getTable:#"PriceList"] query:nil error:nil]];
NSLog(#"tasks count is %d",[tasks count]);
for (int k=0; k<[tasks count]; k++)
{
DBRecord *recordObj=[tasks objectAtIndex:k];
NSString *Tier1_Id =recordObj[#"Tier1"];
NSString *Tier2_Id =recordObj[#"Tier2"];
NSString *Tier3_Id =recordObj[#"Tier3"];
NSString *Code_Id =recordObj[#"Code"];
NSString *CRV_Id =recordObj[#"CRV"];
NSString *insertAdminString = [NSString stringWithFormat:#"INSERT INTO admin_Tbl(Code,Tier1,Tier2,Tier3,CRV) VALUES(\"%#\",\"%#\",\"%#\",\"%#\",\"%#\")",Code_Id,Tier1_Id,Tier2_Id,Tier3_Id,CRV_Id];
BOOL isDataadded = [appdelegate executeInsertQuery:insertAdminString];
if (isDataadded == YES)
{
NSLog(#"admin table insertrd successfully");
}
else
{
NSLog(#"admin table not insertrd successfully");
}
}
}
In Log I am getting tasks count is "0".
I am making a call to syncWithCalendar and after events are successfully added, I get low memory warning and app terminates with "Received Low Memory" warning. The events generated and saved in calendar are more than 50. I tried using instruments but I am not able to find the code where memory leak occurs and also through live bytes that show in instruments I am not able to track the code that is causing the leak. Can anyone please help me solve this issue.
- (void)syncWithCalendar
{
#autoreleasepool {
[self deleteEventsIfExist];
NSMutableDictionary *dictionary = [util readPListData];
NSMutableArray *courses = [util getCourses];
__block NSMutableArray *lessons;
__block NSMutableDictionary *lesson;
NSString *studentID = [util getProgramDetails].studentId;
NSString *programName = [util getProgramDetails].programName;
double offset[] = {0, 0, -300, -900, -1800, -3600, -7200, -86400, -172800};
__block NSString *startDateString = #"", *endDateString = #"";
NSTimeInterval relativeOffsetValue = 0;
int index = [[dictionary objectForKey:#"event-alert-option"] intValue];
relativeOffsetValue = offset[index];
NSDateFormatter *formatter;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSString *currentDateString = [NSString stringWithFormat:#"%# 09:00:00", [formatter stringFromDate:[NSDate date]]];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
NSDate *currentDate = [formatter dateFromString:currentDateString];
EKEventStore *eventStore = [[EKEventStore alloc] init];
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- codes here when user allow your app to access theirs' calendar.
dispatch_async(dispatch_get_main_queue(), ^{
// Event creation code here.
for (int i=0; i<[courses count]; i++)
{
#autoreleasepool {
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
#autoreleasepool {
lesson = [lessons objectAtIndex:j];
NSString *title = nil;
title = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
if ([[lesson objectForKey:#"actual-exam-date"] isEqualToString:#"00/00/0000"])
{
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"plan-exam-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"plan-exam-date"], #"18:00:00"];
}
else
{
if ([[lesson objectForKey:#"retake-actual-date"] isEqualToString:#"00/00/0000"])
{
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"retake-plan-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"retake-plan-date"], #"18:00:00"];
}
}
if (!([startDateString isEqualToString:#""] && [endDateString isEqualToString:#""]))
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title=title;
event.startDate = [formatter dateFromString:startDateString];
event.endDate = [formatter dateFromString:endDateString];
event.allDay = NO;
if (index != 0)
{
event.alarms = [NSArray arrayWithObjects:[EKAlarm alarmWithRelativeOffset:relativeOffsetValue], nil];
}
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
// Compare current date to event start date, if start date has been passed then preventing to sync with calendar
NSComparisonResult result = [event.startDate compare:currentDate];
if (result != NSOrderedAscending)
{
NSError *err = nil;
[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if (err) {
NSLog(#"event not saved .. error = %#",err);
} else {
NSLog(#"event added successfully");
}
}
}
} // autoreleasepool
} // lessons for loop
} // autoreleasepool
} // courses for loop
[self hideModal];
});
}else
{
//----- codes here when user NOT allow your app to access the calendar.
// [self performSelectorOnMainThread:#selector(hideModal) withObject:nil waitUntilDone:NO];
}
}];
} else {
// sync calendar for <iOS6
}
} // autoreleasepool
}
- (void)deleteEventsIfExist
{
#autoreleasepool {
NSMutableArray *courses = [util getCourses];
__block NSMutableArray *lessons;
__block NSMutableDictionary *lesson;
NSString *studentID = [util getProgramDetails].studentId;
NSString *programName = [util getProgramDetails].programName;
EKEventStore* store = [[EKEventStore alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{
// Event creation code here.
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:[[NSDate distantFuture] timeIntervalSinceReferenceDate]];
NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:[NSDate date] endDate:endDate calendars:store.calendars];
NSArray *allEvents = [store eventsMatchingPredicate:fetchCalendarEvents];
for (int i=0; i<[courses count]; i++)
{
#autoreleasepool {
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
#autoreleasepool {
lesson = [lessons objectAtIndex:j];
NSString *oldEventSubtitle = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
for (EKEvent *e in allEvents)
{
if ( [oldEventSubtitle isEqualToString:e.title])
{
NSError* error = nil;
[store removeEvent:e span:EKSpanThisEvent commit:YES error:&error];
NSLog(#"deleting events");
}
}
} // autoreleasepool
} // lessons
} // autoreleasepool
} // courses
});
} // autoreleasepool
}
It's a rough guess, but it seems the asynchronous invocations may lead to troubles.
In order to test this, just use dispatch_sync instead of dispatch_async and examine the memory consumption. If this leads to an improvement, then a solution is in sight, which involves to re-factor your current asynchronous "parallel" approach and turn it into an appropriate asynchronous "serial" approach or an complete synchronous approach.
This may also require to "serialize" all invocations of this asynchronous method:
[eventStore requestAccessToEntityType:EKEntityTypeEvent
completion:^(BOOL granted, NSError *error) {
...
}]
This is how I made a call to syncWithCalendar function
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
NSError *error) {
if (granted){
dispatch_async(dispatch_get_main_queue(), ^{
[self syncWithCalendar];
});
} else {
// calendar access not granted
}
}];
}
And in syncWithCalendar function everything remains same except the line of code that
was creating the crash/memory issue. Below is the incorrect line of code that I was
using earlier
// wrong
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
The correct way to save event: (Note: I didn't require event identifier in my case)
// correct
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:NO error:&err];
and then use [self.eventstore commit:NULL] after all the events are saved. This stopped the crash in my case. Hope this post will
help other get the solution. Thanks !!!!
You need to clear the cache when you are receiving memory warning, use this method it will help you.
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}