Google Plus - Getting Error While Fetching Friends Details - ios

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/

Related

Objective-C using block when get list file using Google Driver API

I am using the Google Drive API. When I use the demo to get the file list I think this app run multi thread. Now I want get file list when method succeeds.
- (void)fetchFiles {
self.output.text = #"Getting files...";
GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
//query.pageSize = 10; /* Total number of files to get at once But useful only when there are more than hundreds of file to get once.*/
query.fields = #"nextPageToken, files(id, name)";
[self.service executeQuery:query delegate:self didFinishSelector:#selector(displayResultWithTicket:finishedWithObject:error:)];
}
link : https://developers.google.com/drive/ios/quickstart
Your can try it.
#property (nonatomic, copy) void(^blockHandler)(id data);
// get list file
- (void)listFiles:(NSString *)fileId complete:(void(^)(id data))completion {
self.blockHandler = completion;
GTLRDriveQuery_FilesList *query = [GTLRDriveQuery_FilesList query];
query.fields = #"nextPageToken, files(id, name, thumbnailLink, webViewLink)";
query.pageSize = 1000;
query.q = [NSString stringWithFormat:#"'%#' In parents and trashed=false",fileId];
[self.service executeQuery:query
delegate:self
didFinishSelector:#selector(displayResultWithTicket:finishedWithObject:error:)];
}
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
finishedWithObject:(GTLRDrive_FileList *)result
error:(NSError *)error {
if (error == nil) {
NSMutableString *output = [[NSMutableString alloc] init];
if (result.files.count > 0) {
[output appendString:#"Files:\n"];
for (GTLRDrive_File *file in result.files) {
itemGG *temp = [[itemGG alloc] initWithName:file.name linkThumb:file.thumbnailLink fileID:file.identifier];
[self.lstItem addObject:temp];
[output appendFormat:#"%# (%#)\n", file.name, file.identifier];
}
} else {
[output appendString:#"No files found."];
}
NSLog(#"%#", output);
} else {
NSLog(#"Error getting presentation data: %#\n", error.localizedDescription);
}
if (self.blockHandler) {
self.blockHandler([[NSArray alloc] initWithArray:self.lstItem]);
}
}
__weak typeof(self) w = self;
[self.cloud listFiles:#"root" complete:^(id data) {
w.tableData = data;
[w.myCollection reloadData];
}];

Getting data from a services Objective c

I have got a small problem with the below service data
{
"DataTable": {
"DataList1": {
"StudentName": "Rakesh",
"StudentId": "13",
"StudentAge": "19",
"StudentAddress": "NewYork",
},
"DataList2": [{
"TeacherName": "Abhinav",
"TeacherId": "309",
"TeacherAge": "34",
"TeacherAddress": "NewYork",
}]
}
}
i Can get the data from DataList1 and cannot know how to get the data from DataList2. Below is the code what i have tried. Please help to find out the solution. Thanks in Advance
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSMutableDictionary *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Information" message:#"Currently there are no Data" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert setTag:1];
[alert show];
}else {
[myArray addObject:[sdf objectForKey:#"DataList1"]];
jsonArray=[myArray mutableCopy];
refilldict=[jsonArray objectAtIndex:0];
NSArray *keys = [refilldict allKeys];
for(int p=0 ; p<[keys count]; p++ )
{
NSString *value=[refilldict objectForKey:[keys objectAtIndex:p]];
if ([value isEqual: [NSNull null]]||[value length]==0) {
[refilldict setValue:#"" forKey:[keys objectAtIndex:p]];
}
}
lblStudentName.text = [refilldict objectForKey:#"StudentName"];
lblStudentId.text = [refilldict objectForKey:#"StudentId"];
lblStudentAge.text = [refilldict objectForKey:#"StudentAge"];
lblStudentAddress.text = [refilldict objectForKey:#"StudentAddress"];
}
self.navigationController.navigationBar.userInteractionEnabled = YES;
[HUD hide:YES];
[HUD removeFromSuperview];
HUD=nil;
}
Please use the bellow code and pass your Initial Json dictionary in it.
-(void)parseJsonData:(NSDictionary *)jsonDictionary{
for(int i=0;i<[jsonDictionary allKeys].count;i++){
NSString *keyName = [[jsonDictionary allKeys] objectAtIndex:i];
id objValue = [jsonDictionary objectForKey:keyName];
if([objValue isKindOfClass:[NSArray class]]){
NSArray *dataList2Array = (NSArray *)objValue;
NSLog(#"DataList2 Is :--%#",dataList2Array);
}
else {
NSDictionary *dataList1 = (NSDictionary *)objValue;
NSLog(#"DataList1 Is :--%#",dataList1);
}
}
}
you can get easily like
[myArray addObject:[sdf objectForKey:#"DataList1"]];
its started with array of dictionary , so you need to store your second object to array and take from index.
NSArray *temp = [sdf objectForKey:#"DataList2"];
if(temp.count >0)
{
lblTeacherName.text = temp[0][#"TeacherName"];
lblTeacherId.text = temp[0][#"TeacherId"];
lblTeacherAge.text = temp[0][#"TeacherAge"];
lblTeacherAddress.text = temp[0][#"TeacherAddress"];
}

AWS SDK for IOS from v1 to v2 about the "S3objectsummary"

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.

Uploading a video on youtube gives error ios

I am using this code to upload videos to Youtube through my application - Uploading Videos on youtube . Now the thing is, the video is never being uploaded and I am wlways getting this error :
serviceBase:<GDataServiceGoogleYouTube: 0x155e3710> objectFetcher:<GDataHTTPUploadFetcher: 0x15662c10> failedWithStatus:400 data:<errors xmlns='http://schemas.google.com/g/2005'><error><domain>GData</domain><code>InvalidRequestUriException</code><internalReason>Exception message unavailable</internalReason></error></errors>
No matter what I do. My upload code for Youtube is as below :
- (void)uploadPressed{
NSString *devKey = #"some key";
GDataServiceGoogleYouTube *service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];
NSString *kGDataServiceDefaultUser = #"isome#gmail.com";
NSString *clientID = #"googleusercontent.com";
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:kGDataServiceDefaultUser
clientID:clientID];
// load the file data
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"vid1.mp4"];
NSData *myData = [[NSData alloc] initWithContentsOfFile:appFile] ;
// gather all the metadata needed for the mediaGroup
NSString *titleStr = #"Survey App";
GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = #"Comedy";
GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = #"Survey Description.";
GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = #"survey";
GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
BOOL isPrivate = YES;
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:documentsDirectory
defaultMIMEType:#"video/mp4"];
// create the upload entry with the mediaGroup and the file data
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:myData
MIMEType:mimeType
slug:#"vid1.mp4"];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
}
#pragma mark -
- (GDataServiceGoogleYouTube *)youTubeService {
static GDataServiceGoogleYouTube* service = nil;
if (!service) {
service = [[GDataServiceGoogleYouTube alloc] init];
[service setShouldCacheDatedData:YES];
[service setServiceShouldFollowNextLinks:YES];
[service setIsServiceRetryEnabled:YES];
}
// update the username/password each time the service is requested
NSString *kGDataServiceDefaultUser = #"isome#gmail.com";
NSString *password = #"passwrd";
[GDataHTTPFetcher setIsLoggingEnabled:YES];
if ([kGDataServiceDefaultUser length] > 0 && [password length] > 0) {
[service setUserCredentialsWithUsername:kGDataServiceDefaultUser
password:password];
} else {
// fetch unauthenticated
[service setUserCredentialsWithUsername:nil
password:nil];
}
NSString *devKey = #"some key";
[service setYouTubeDeveloperKey:devKey];
return service;
}
// progress callback
- (void)ticket:(GDataServiceTicket *)ticket
hasDeliveredByteCount:(unsigned long long)numberOfBytesRead
ofTotalByteCount:(unsigned long long)dataLength {
// [mProgressView setProgress:(double)numberOfBytesRead / (double)dataLength];
}
// upload callback
- (void)uploadTicket:(GDataServiceTicket *)ticket
finishedWithEntry:(GDataEntryYouTubeVideo *)videoEntry
error:(NSError *)error {
if (error == nil) {
// tell the user that the add worked
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Uploaded!"
message:[NSString stringWithFormat:#"%# succesfully uploaded",
[[videoEntry title] stringValue]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:[NSString stringWithFormat:#"Error: %#",
[error description]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
}
// [mProgressView setProgress: 0.0];
[self setUploadTicket:nil]

Sqlite sync with iCloud not updating data

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

Resources