How can I download Docs to Iphone using GoogleDocAPI - iphone

Is it possible to download the documents from my gmail account to documents folder for iphone app. Actually i used Google Doc API and get Feed by using
-(GDataServiceGoogleDocs *)getdocservice
{
static GDataServiceGoogleDocs *docs = nil;
if(!docs)
{
docs = [[GDataServiceGoogleDocs alloc]init];
[docs setShouldCacheResponseData:YES];
[docs setServiceShouldFollowNextLinks:YES];
[docs setIsServiceRetryEnabled:YES];
[docs setUserCredentialsWithUsername:#"gmailaccount#gmail.com" password:#"password"];
}
return docs;
}
//##############
GDataServiceTicket *ticket;
#pragma mark docService
docsService = [self getdocservice];
NSURL *feedURL = [GDataServiceGoogleDocs docsFeedURL];
GDataQueryDocs *queryDocs = [GDataQueryDocs documentQueryWithFeedURL:feedURL];
[queryDocs setMaxResults:1000];
[queryDocs setShouldShowFolders:YES];
ticket = [docsService fetchFeedWithQuery:queryDocs delegate:self didFinishSelector:#selector(docsFetchTicket:finishedWithFeed:error:)];
// call back
-(void)docsFetchTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataFeedDocList *)feed error:(NSError *)error
{
GDataFeedDocList *mDocListFeed = feed;
int numDocs = [[feed entries] count];
NSLog(#"NumDocs :%d\n Feed :%#",numDocs,mDocListFeed);
for (int i=0; i<numDocs; i++) {
GDataEntryDocBase *docEntry = [mDocListFeed entryAtIndex:i];
NSLog(#"\n############ DocTitle :%#\n\n",[[docEntry content] sourceURL] );
}
}
it is displaying all the documents from my account .
But i am not getting how to download those documents into my app document folder. If any one have idea please help me.

(Disclaimer: I am not proficient in Objective-C)
Each entries of the GDataFeedDocList should contain a link which points to the actual file's data. The link is contained in its "Content" attribute. In your code it seems that you have that URL (sourceURL) you need to download the content using an authenticated request to taht URL.
You should also now use the newer Drive API instead of the DocumentList API using the newer Objective-C client library:
http://code.google.com/p/google-api-objectivec-client/

Related

How to import an .sqlite3/.sqlite file to ios application?

I was having an excel file.
I have converted that file to .csv format and import that file to base and converted it into .sqlite file.
So the question is that:
Is there any way to import it into an ios app and manipulate the data.
Is there any way to use it like core data or import that file into core data.
Kindly refer any good tutorial preferably video tutorial or some other good one.
You can use it directly with FMDB library: https://github.com/ccgus/fmdb
Another option is to import that file into core data, but it is a little tricky. You can do it if you follow these steps:
Create empty SQLite database in your application and run your app in simulator.
Open simulator directory on your computer and locate SQLite database file.
Look inside it with SQLite command line tool or something like "SQLite Data Browser" GUI tool (http://sqlitebrowser.sourceforge.net/).
Import your data to this database file without changing structure and data in core data meta tables.
Finally you have SQLite database file ready to be used with core data. So you put it into your app bundle.
On first application launch you should copy your SQLite database file to appropriate directory (you know where you should put your file - you already found it in simulator app directory) before configuring core data stack.
It sounds a bit complicated but it works ;)
Nice article about shipping pre-populated data for core data: http://www.objc.io/issue-4/importing-large-data-sets-into-core-data.html
Update
Please note the updated response.
Is there any way to import it (SQLite) into an ios app and manipulate the data?
You can import a sqlite file into Xcode, by simply adding it as a resource using Add New File... However you would have limited ability to use it jointly with Core Data (unless it was created with Core Data). One can review the objc.io article referenced earlier that covers how to deal with prepopulated data in an Xcode project. Here is the pertinent section of that article.
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError *error;
if([fileManager fileExistsAtPath:self.storeURL.path]) {
NSURL *storeDirectory = [self.storeURL URLByDeletingLastPathComponent];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:storeDirectory
includingPropertiesForKeys:nil
options:0
errorHandler:NULL];
NSString *storeName = [self.storeURL.lastPathComponent stringByDeletingPathExtension];
for (NSURL *url in enumerator) {
if (![url.lastPathComponent hasPrefix:storeName]) continue;
[fileManager removeItemAtURL:url error:&error];
}
// handle error
}
NSString* bundleDbPath = [[NSBundle mainBundle] pathForResource:#"seed" ofType:#"sqlite"];
[fileManager copyItemAtPath:bundleDbPath toPath:self.storeURL.path error:&error];
NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
NSString* bundleVersion = [infoDictionary objectForKey:(NSString *)kCFBundleVersionKey];
NSString *seedVersion = [[NSUserDefaults standardUserDefaults] objectForKey:#"SeedVersion"];
if (![seedVersion isEqualToString:bundleVersion]) {
// Copy the seed database
}
// ... after the import succeeded
[[NSUserDefaults standardUserDefaults] setObject:bundleVersion forKey:#"SeedVersion"];
Assuming one wanted to import a CSV file rather than an Excel or SQLite... Since this is a common question, here is a simple parser that one can use to incorporate CSV data into an Xcode project.
func parseCSV (contentsOfURL: NSURL, encoding: NSStringEncoding, error: NSErrorPointer) -> [(name:String, detail:String, price: String)]? {
// Load the CSV file and parse it
let delimiter = ","
var items:[(name:String, detail:String, price: String)]?
if let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) {
items = []
let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]
for line in lines {
var values:[String] = []
if line != "" {
// For a line with double quotes
// we use NSScanner to perform the parsing
if line.rangeOfString("\"") != nil {
var textToScan:String = line
var value:NSString?
var textScanner:NSScanner = NSScanner(string: textToScan)
while textScanner.string != "" {
if (textScanner.string as NSString).substringToIndex(1) == "\"" {
textScanner.scanLocation += 1
textScanner.scanUpToString("\"", intoString: &value)
textScanner.scanLocation += 1
} else {
textScanner.scanUpToString(delimiter, intoString: &value)
}
// Store the value into the values array
values.append(value as! String)
// Retrieve the unscanned remainder of the string
if textScanner.scanLocation < count(textScanner.string) {
textToScan = (textScanner.string as NSString).substringFromIndex(textScanner.scanLocation + 1)
} else {
textToScan = ""
}
textScanner = NSScanner(string: textToScan)
}
// For a line without double quotes, we can simply separate the string
// by using the delimiter (e.g. comma)
} else {
values = line.componentsSeparatedByString(delimiter)
}
// Put the values into the tuple and add it to the items array
let item = (name: values[0], detail: values[1], price: values[2])
items?.append(item)
}
}
}
return items
}
(Source article)
Another option is to use the Core Data Editor tool originally mentioned in the Ray W. list of tools. This GUI editor tries to make handling CSV data imports easier.
Is there any way to use it like core data or import that file into core data?
So a SQLite database is not the same as Core Data (which is an object graph persistence...). I was about to go into my diatribe here, but Apple's Core Data FAQ says it better than I could...:
How do I use my existing SQLite database with Core Data?
You don’t. Although Core Data supports SQLite as one of its persistent
store types, the database format is private. You cannot create a
SQLite database using native SQLite API and use it directly with Core
Data (nor should you manipulate an existing Core Data SQLite store
using native SQLite API). If you have an existing SQLite database, you
need to import it into a Core Data store (see Efficiently Importing
Data).
So that's the official answer. Anything else offered is just a way to work around the fact that one is not supposed to do this.
However, given that you also have a CSV file you do have some other options. In the past I've built a file reader to examine the contents of a CSV file using a stream reader. Here is the gist of that, however my file likely had some other formatting so this probably needs tweaking. You can also look at using any object that reads the contents of a file. For example; a much simpler technique comes to mind:
Use the initWithContentsOfFile on the NSString class
Gives you a string with the CSV in memory
Iterate the string for each line
Loop through the line using commas and do something with each piece of data
NSString *fileContents = [NSString stringWithContentsOfFile:#"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
//loop and split each line in lines array into useful data
Let's say you really want to use SQLite in iOS, warnings notwithstanding... You can add the sqlite3 library to your project. Full details are available on how to use SQLite instead of Core Data. One of the many online tutorials is at AppCoda
The basics are covered (sample project):
Saving...
- (IBAction)saveInfo:(id)sender {
// Prepare the query string.
NSString *query = [NSString stringWithFormat:#"insert into peopleInfo values(null, '%#', '%#', %d)", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];
// Execute the query.
[self.dbManager executeQuery:query];
// If the query was successfully executed then pop the view controller.
if (self.dbManager.affectedRows != 0) {
NSLog(#"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);
// Pop the view controller.
[self.navigationController popViewControllerAnimated:YES];
}
else{
NSLog(#"Could not execute the query.");
}
}
Editing...
-(void)loadInfoToEdit{
// Create the query.
NSString *query = [NSString stringWithFormat:#"select * from peopleInfo where peopleInfoID=%d", self.recordIDToEdit];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// Set the loaded data to the textfields.
self.txtFirstname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"firstname"]];
self.txtLastname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"lastname"]];
self.txtAge.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"age"]];
}
Deleting...
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the selected record.
// Find the record ID.
int recordIDToDelete = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];
// Prepare the query.
NSString *query = [NSString stringWithFormat:#"delete from peopleInfo where peopleInfoID=%d", recordIDToDelete];
// Execute the query.
[self.dbManager executeQuery:query];
// Reload the table view.
[self loadData];
}
}
Re: Kindly refer any good tutorial preferably video tutorial or some
other good one.
The following tutorial should fill your need. There are quite a few tutorials on this topic you can check out www.lynda.com for a detailed walk through on building an iOS app with SQLite (some cost involved for full access however search Youtube as they post sample movies covering these topics all the time).
http://www.youtube.com/watch?v=bC3F8a4F_KE (see 1:17 in video)
If you have an .sql file, you just import it to your project by going to File - Add Files.
Also, keep in mind that if you leave your .sql file in your bundle, it will be read only.
So, unless you want it to be read only, you should make new group and put your .sql there.

Facebook installed parameter not returning data

I am attempting to determine who among my facebook friends are currently using my app. The general wisdom, as far as I can tell, is to use the graph api, and send the 'installed' parameter when getting your friends list. This does not seem to be working for me, and I am wondering where I am going wrong. This is my code:
First, the permissions in effect:
_facebookPermissions = #[#"publish_stream", #"read_stream", #"friends_photos", #"user_photos"];
Now the SLRequest and it's setup:
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"fbUserID"];
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#/friends", username];
NSURL *friendsList = [NSURL URLWithString:urlString];
NSDictionary *friendsListParameters = #{#"fields": #"id,name,picture,installed"};
SLRequest *getFriends = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:friendsList parameters:friendsListParameters];
Now a sample result:
{
id = 10000123456911;
name = "Don Dobrian";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash3/41664_100001237218111_2269_q.jpg";
};
};
},
As you can see, the permissions will get me almost everything. But there is no indication at all that the 'installed' parameter was even noticed. So here are my questions, the answer to any one of which would solve my problem:
Is this how you do it? What permissions are you using to get the 'installed' status?
Is there a better way to get this information using the iOS Social Framework?
As it happens, Ming Li was dead on with his assessment. The parameter is returned only if the friend has the app installed. An example of each:
},
{
id = 12645478730;
installed = 1;
name = "Edwin Robertson";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/...";
};
};
},
{
id = 12645478730;
name = "Greg Walker";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net...";
};
};
},
What is odd is that I was certain this did not work as expected a couple months ago when I last worked on it. Perhaps FB silently fixed something, perhaps my test user was having some issues, maybe I was just too tunnel visioned to see the fix in front of me. Who knows. But if you follow my method above, you should get this result. Good luck!

Using Obj-C generated code using WSDLToObj-c Tool

From my application i need to call a web service to get the list of books in a server. For this purpose the following WSDL link is provided http://demo.kitaboo.com/eBookServices/services/ListOfBooksService?wsdl
Using the WSDL2ObjC Tool available at http://code.google.com/p/wsdl2objc/downloads/list i've generated the equivalent objective-C code for the given WSDL url.
This is the link which i referred while implementing to call the web service.
#import "MyWebService.h"
MyWebServiceBinding *binding = [MyWebService MyWebServiceBinding];
binding.logXMLInOut = YES;
ns1_MyOperationRequest *request = [[ns1_MyOperationRequest new] autorelease];
request.attribute = #"attributeValue";
request.element = [[ns1_MyElement new] autorelease];
request.element.value = #"elementValue"];
MyWebServiceBindingResponse *response = [binding myOperationUsingParameters:request];
NSArray *responseHeaders = response.headers;
NSArray *responseBodyParts = response.bodyParts;
for(id header in responseHeaders) {
if([header isKindOfClass:[ns2_MyHeaderResponse class]]) {
ns2_MyHeaderResponse *headerResponse = (ns2_MyHeaderResponse*)header;
// ... Handle ns2_MyHeaderResponse ...
}
}
for(id bodyPart in responseBodyParts) {
if([bodyPart isKindOfClass:[ns2_MyBodyResponse class]]) {
ns2_MyBodyResponse *body = (ns2_MyBodyResponse*)bodyPart;
// ... Handle ns2_MyBodyResponse ...
}
}
I'm unable to interrelate the terms such as (ns1_MyOperationRequest, MyWebServiceBindingResponse, myOperationUsingParameters) that are present in the code.
Any idea on how to go about doing this?
EDIT for your updated question:
In your header file, add the ListOfBooksServiceSoapBindingResponseDelegate and also implement - (void) operation:(ListOfBooksServiceSoapBindingOperation *)operation completedWithResponse:(ListOfBooksServiceSoapBindingResponse *)response;
Check the instructions:
Once you obtain WSDL2ObjC, code generation is pretty simple.
Launch the app
Browse to a WSDL file or enter in a URL
Browse to an output directory
Click "Parse WSDL"
Source code files will be added to the output directory you've
specified. There will be one pair of .h/.m files for each namespace in
your WSDL.
In case you didn't notice, you must have downloaded a standalone WSDL2ObjC.app. The window looks like this:
Just enter your WSDL link in link and get the code
http://sudzc.com/

Obtaining Specific ABSource from ABAddressBook in iOS 4+

Does anyone have an example of how to obtain a specific ABSource from the ABAddressBook in iOS 4+?
iOS 4+ provides new API that allows one to select a specific ABSource from the ABAddressBook. This may be useful as some operations, e.g. creating an ABGroup, are not supported in some sources (i.e. Exchange).
"Not all source types support groups, more conspicuously, Exchange does not know anything about groups." - http://flavors.me/volonbolon#1a5/tumblr
Attached are functions that leverage the new API to obtain sources of specific types which may be used in calls to ABGroupCreateInSource().
#define CFRELEASE_AND_NIL(x) CFRelease(x); x=nil;
ABRecordRef sourceWithType (ABSourceType mySourceType)
{
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef sources = ABAddressBookCopyArrayOfAllSources(addressBook);
CFIndex sourceCount = CFArrayGetCount(sources);
ABRecordRef resultSource = NULL;
for (CFIndex i = 0 ; i < sourceCount; i++) {
ABRecordRef currentSource = CFArrayGetValueAtIndex(sources, i);
CFTypeRef sourceType = ABRecordCopyValue(currentSource, kABSourceTypeProperty);
BOOL isMatch = mySourceType == [(NSNumber *)sourceType intValue];
CFRELEASE_AND_NIL(sourceType);
if (isMatch) {
resultSource = currentSource;
break;
}
}
CFRELEASE_AND_NIL(addressBook);
CFRELEASE_AND_NIL(sources);
return resultSource;
}
ABRecordRef localSource()
{
return sourceWithType(kABSourceTypeLocal);
}
ABRecordRef exchangeSource()
{
return sourceWithType(kABSourceTypeExchange);
}
ABRecordRef mobileMeSource()
{
return sourceWithType(kABSourceTypeMobileMe);
}
Really wanna know how to create my own source.Just like the group Exchange create with which you dont need to edit the default source record but create own one,and what's most fantastic is,the addressbook will linked them together automatically.
Xyzzycoder-
Your solution works well if there is already a localSource, but just returns NULL if there isn't one.
Is there a way to, say, create an ABRecordRef for a localSource? I need to be able to store my contact to a non-synchronising source.
Cheers
The code has errors, thats why it always returns two, since the method: ABRecordGetRecordType is not a part of the ABSource. It only includes:
kABPersonType for person records
kABGroupType for group records.
kABSourceType for source records.
To figure out the right type you have to use: ABRecordCopyValue(source, kABSourceTypeProperty) instead! :) Works excellent on my iPhone with or without localSource.
Good luck!

search text in pdf in iphone

I am trying to do search functionality in iPhone. I pass the page number and the string to be searched.. but it is not getting the proper output.
in contentStream I get nothing. I got this code by googling. I don't know what will be there in contentStream object.
-(BOOL)page:(CGPDFPageRef)inPage containsString:(NSString *)inSearchString {
[self setCurrentData:[NSMutableString string]];
CGPDFContentStreamRef contentStream = CGPDFContentStreamCreateWithPage(inPage);
CGPDFScannerRef scanner = CGPDFScannerCreate(contentStream, table, self);
bool ret = CGPDFScannerScan(scanner);
CGPDFScannerRelease(scanner);
CGPDFContentStreamRelease(contentStream);
return ([[currentData uppercaseString]
rangeOfString:[inSearchString uppercaseString]].location != NSNotFound);
}
If there is any other solution then also it is fine.
YOU SHOULD IMPLEMENT THE COMPLETE CODE
http://www.random-ideas.net/posts/42%22
check out the above link
a complete code to do so.
Check out this question and its answers for more information: PDF search on the iPhone