Using Obj-C generated code using WSDLToObj-c Tool - iphone

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/

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.

How to convert text file to xml in xcode

I have a big text file that I want to convert into Xcode. I added the text file in the main bundle (drag and drop) into my project . I can see the text file viewDidLoad.
But I like to convert it to XML file. For instance my file looks like :
asasasasasas
wewewewewewe
qwqwqwqwqwqw
xyz_ 22 aaaaaaaaaaa
fgfgfgfgfgfgfg
ererererererer
abc_ 12 bbbbbbbbbb
jkjkjkjkjkjkjk
lalallalalalal
In the above mentioned, I want to eliminate the first 3 lines, to start from xyz_ 22 as (parent), jkjkjkj as child lalalala as a child.
I need only the idea how to implement this ... I'll write the code :)
mycode:
- (IBAction)readUsingObjectiveC:(id)pId {
NSString * zStr = [NSString stringWithContentsOfFile:#"/Users/dd007/Desktop/abc.txt" encoding:NSASCIIStringEncoding error:NULL];
NSLog(#"readUsingObjectiveC zStr=\n%#",zStr);
// now to extract the data line by line
NSArray * zAryOfLines = [zStr componentsSeparatedByString:#"\n"];
if([zAryOfLines count] == 0)
{
NSLog(#"readUsingObjectiveC zAryOfLines count = 0");
return;
}
//for (int i=0; i<([zAryOfLines count]-30); ++i)
for ( int i=30; i<zAryOfLines ; i++)
{
if([[zAryOfLines objectAtIndex:i] isEqualToString:#"xyz_ "])
{
NSLog(#"<msg1>%#<msg1/>\n",[zAryOfLines objectAtIndex:i]);
NSLog(#"<msg2>%#<msg2/>\n",[zAryOfLines objectAtIndex:i+1]);
NSLog(#"<msg3>%#<msg3/>\n",[zAryOfLines objectAtIndex:i+2]);
[zArrayOfLines writeToFIle:#"/.....documents/..save.xml" automatically:YES encodingNSASCIIStringEncoding error:NULL];
}
}
I am getting convert into xml format but i like to save the file in .xml .. but i am getting error could any one tell me where i am doing mistake ??????
You can't convert a file to xml using XCode, you have two options:
You can create a python or ruby script that parses your file and makes a XML file, and then use a xml parser,
Or you can create a class that parses your plain file with the rules you want.
I think you want to transform a .txt to a .xml so for make this i read the .txt to a nsstring i cut this into a NSArray with componentsSeparatedByString:#"\n" method of NSString (take care of \r character) and after just don't take line you don't want and create a new NSString for add tag XML to your line if you now where place the good tag or check it with the contains of your line in the NSArray for finish just saved in new file with extension .xml.
If you need help for write code like i describe say it.
There is no option for converting the text to xml directly in iOS.
But you can do it by passing the data manually.
You can use either libXml framework or GDataXml for doing this.
For libXml xml generation sample code go to this link and download Chapter 10.zip
Please check this tutorial for Read and Write XML Documents with GDataXML
Also TCMXMLWriter is an opensource xmlgenerator :
I think a code like this work for your example :
NSString *contentFile = [[NSString alloc] initWithContentsOfFile:pathFile encoding:NSUTF8StringEncoding error:nil];
NSArray *lineFile = [contentFile componentsSeparatedByString:#"\n"];
NSMutableString *xmlFile = [[NSMutableString alloc] init];
For(int i = 3; i < lineFile.count; i++)//i = 3 for don't take the 3 first line
{
if ([((NSString *)[lineFile objectAtIndex:i]) rangedOfString:#"test"].location != NSNotFound)
{
xmlFile = [NSString stringWithFormat:#"%#<nameTag>%#</nameTag>", xmlFile, (NSString *)[lineFile objectAtIndex:i]];
}
else if ...
}
And save he nsstring in new file. Possible in loop to make by number like if i is multiple of 3 of 4 etc...

RestKit object mapping failing in one project but not in Twitter example

Learning RESTKit.
Step 1: I have successfully run the Twitter example project.
Step 2: I have successfully modified the Twitter project to point to my own REST webservice... REST is able to interpret the results successfully, and map them to a custom object I built.
Step 3: I have created my own project space and copy-pasted the working code from Step 2 into this project with some minor edits, and strangely enough, RESTKit is failing to properly map the results. I am going crazy at this point.
Turning on the handy debugging traces included in RESTKit, both projects get to here:
2012-08-12 21:06:14.145 RKTwitter[9087:13003] D restkit.object_mapping:RKObjectMapper.m:320 Performing object mapping sourceObject
But Step2 Project gets this as the next message:
2012-08-12 21:06:14.294 RKTwitter[9087:13003] T restkit.object_mapping:RKObjectMapper.m:278 Examining keyPath '' for mappable content...
2012-08-12 21:06:14.301 RKTwitter[9087:13003] D restkit.object_mapping:RKObjectMapper.m:261 Found mappable collection at keyPath ''...
whereas my Step3 project gives up and dies:
2012-08-12 21:10:40.912 DogPark[9127:13203] D restkit.object_mapping:RKObjectMapper.m:351 The following operations are in the queue: ()
Rolled up my sleeves, and I have determined the precise point where the difference in code execution occurs within RESTKit:
In RKObjectMappingProvider.m, line 160 is the following method:
- (id)valueForContext:(RKObjectMappingProviderContext)context {
NSNumber *contextNumber = [NSNumber numberWithInteger:context];
return [mappingContexts objectForKey:contextNumber];
}
Which for Step2 returns a dictionary with 1 element in it, whereas my Step3 project returns a dictionary with 0 elements in it. This dictionary is used in RKObjectMapper.m, at line 332, where the foundMappable is either true for Step2 project or false for my Step3.
if ([mappingsForContext isKindOfClass:[NSDictionary class]]) {
results = [self performKeyPathMappingUsingMappingDictionary:mappingsForContext];
foundMappable = (results != nil);
Here is the code that seems correct but doesn't seem to want to run properly:
// init the Object Manager
RKURL *baseURL = [RKURL URLWithBaseURLString:SERVER_ADDRESS];
RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:baseURL];
objectManager.client.baseURL = baseURL;
// Mapping
RKObjectMapping *ownerMapping = [RKObjectMapping mappingForClass: [DogOwner class]];
[ownerMapping mapKeyPath:#"DogOwnerId" toAttribute:#"dogOwnerID"];
[ownerMapping mapKeyPath:#"DogName" toAttribute:#"dogName"];
[ownerMapping mapKeyPath:#"OwnerFirstName" toAttribute:#"ownerFirstName"];
[[RKObjectManager sharedManager].mappingProvider setObjectMapping:ownerMapping forResourcePathPattern:#"/DogOwner"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath: #"/dogowner" delegate:self];
Any ideas?
Thank you for the very comical narration to your problem.
One mistake was specifying a mapping to /Dogowner and trying to load /dogowner. Your comment above also gives two other huge problems
xml and json are not interchangable
your source keypath was wrong.

How can I download Docs to Iphone using GoogleDocAPI

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/

xml parsing iphone, objective C?

i want to get data between xml tags? how to navigate? and get values..
im using wsdl2objc from google code:http://code.google.com/p/wsdl2objc/
output soapbody follows:
read instruction here: http://code.google.com/p/wsdl2objc/wiki/UsageInstructions
my header file: #import "MService.h"
how to get image source and text value????
please help me....
if([bodyPart isKindOfClass:[types_getFavoriteColorResponseType class]]) {
types_getFavoriteColorResponseType *body = (types_getFavoriteColorResponseType*)bodyPart;
// Now you can extract the color from the response
q.text = body.color;
continue;
}
Ок as far as I understand this is a part which extracts text data from your SOAP response.
BTW you need response to be processed via SAX or DOM? First example in given URL refers to DOM usage, whereas the second to SAX.
More than that I can not tell. Guess you have to read manual or find someone, who worked with this.
Use NSXMLParser, NSXMLParserDelegate for xml parsing, you can get the callbacks with proper values:
parser:didStartElement:namespaceURI:qualifiedName:attributes:
parser:foundCharacters:
parser:didEndElement:namespaceURI:qualifiedName:
Ref: http://developer.apple.com/library/ios/#documentation/cocoa/reference/NSXMLParserDelegate_Protocol/Reference/Reference.html
hey i got the result using sudzc.com
if ([result isKindOfClass:[MSalesPages class]]) {
NSLog(#"Response");
NSMutableArray* pageData = result.PageData;
for(MSalesPage* page in pageData){
NSLog(#"Inside for loop %#", page.Id);
NSMutableArray* images = page.Images;
NSMutableArray* textData = page.TextData;
for(MSalesImg* img in images){
NSLog(#"Image url %#",img.Src);
}
for(MSalesText* text in textData){
NSLog(#"Product Name %#",text.Value);
}
}
}
carefully check with the above xml, u will get the answer :)