I want to get all the results of a sql table's call (select *) in php, to send them to the iphone's app and use them there.
What steps would you recommend me?
I am a complete noob in xcode and php. I have some tests like this one:
NSString *miURL = [NSString stringWithFormat:#"http://hello.com/test.php];
NSString *myRawJson = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:miURL]];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *list = [NSArray alloc];
lista = [[parser objectWithString:myRawJson error:nil] copy];
And in the .php:
<?php
$conectID = mssql_connect("SERVIDOR\SQLEXPRESS","**","**");
mssql_select_db("Animals");
$result=mssql_query("select * from dbo.animals where name='jack'");
$row=mssql_fetch_array($result);
if ($row){
$myArray = array($row["name"], $row["type"], $row["colour"], $row["age"], $row["address"]);
echo json_encode($myArray);
}
All of this is good and quick for a simple line.. but for a lot of lines from a sql's select would be very inefficient, doesn't it?
Because I would like to execute for example: "select * from dbo.animals" and save each field of the table in its counterpart xcode's object's field. In xcode I would have a list of this:
#interface DataPerfil : NSObject {
NSString *name;
NSString *type;
NSString *colour;
NSInteger *age;
NSString *address;
}
....
I hope I have explained it well..
Sorry my bad english and thanks.
If you're talking real web service as in soap here is a tutorial I used :
http://www.devx.com/wireless/Article/43209/0/page/1
It's more complex than your example but the web service layer adds security and hides the access to data.
Related
I have a NSString that should be constant in my class. I used the following code to accomplish this:
#interface DefinitionViewController ()
#end
static NSString *preamble;
#implementation DefinitionViewController {
}
+(void)initialize {
if (self == [DefinitionViewController class]) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"preamble" ofType:#"html"];
preamble = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding
error:nil];
}
}
It seems to work fine. I worry about using a file read inside an initialize. Is there a more appropriate means to accomplish the same goal (shared static string)? I could bury this inside my code, but it was much easier to maintain the somewhat large string as an external file.
Thanks for any advice.
"I worry about using a file read inside an initialize".
Don't (worry). The fact that it is, for example, a class method is utterly irrelevant. It is code. It runs and does its job. It is sound code, it runs coherently at a coherent time, and your app bundle is a real thing that really contains the resource. There's no problem here.
If you want to postpone creation of the string, and make assurance doubly sure that the string is not initialized twice, you could instead use a singleton pattern so that the string value is not generated until the first time it is explicitly requested:
+ (NSString*) preamble {
static NSString* preamble = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *path = [[NSBundle mainBundle] pathForResource:#"preamble" ofType:#"html"];
preamble = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
});
return preamble;
}
But there is no special need for this. (EDIT: But see, to the contrary, the comment below of #bbum, who Really Knows Stuff.)
I made server side by Python and which return some scraped html string to client side which is made by Objective-C.
But When I try to show from client side which retuned string from server , it contains –,„,etc.But I don't know why it contains above characters.
Do you have any idea? And I want to convert them correctly with Objective-C. Do you have any idea? Thanks in advance.
If you want to stick with Cocoa you could also try to use NSAttributedString and initWithHTML:documentAttributes:, you will lose the markup than, though:
NSData *data = [#"<html><p>– Test</p></html>" dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil];
NSString *result = [string string];
These are HTML Entities
Here is NSString category for HTML and here are the methods available:
- (NSString *)stringByConvertingHTMLToPlainText;
- (NSString *)stringByDecodingHTMLEntities;
- (NSString *)stringByEncodingHTMLEntities;
- (NSString *)stringWithNewLinesAsBRs;
- (NSString *)stringByRemovingNewLinesAndWhitespace;
I have a NSMutableArray in an object.
In an object-method, I do something like this:
/* ... */
[[LRResty client] get:connectURL withBlock:^(LRRestyResponse *r) {
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonResponse = [jsonParser objectWithString:[r asString]];
NSDictionary *permittedBases= [jsonResponse objectForKey:#"permittedBases"];
Database *database = [[Database alloc] init];
for (id key in permittedBases) {
/* ... */
[workingDatabases addObject:database];
}
}];
return workingDatabases;
At the return line, there are no objects in my array (anymore). I am aware of the fact, that the 'database'-objects are going out of scope. But I am saving them in the array.
Am I overseeing something?
If it is of any help, here is the header file:
#class Database;
#interface CommunicationHelper : NSObject {
NSMutableArray *workingDatabases;
}
// The function where the problem appears:
- (NSMutableArray *)getDatabasesForWebsite:(Website *)websiteIn;
#property(nonatomic,copy) NSMutableArray *workingDatabases;
#end
just allocate your workingDatabases (Mutable array) somewhere before using that array.
Once you allocate it,It will work fine.
I assume it's because [LRResty client] get: is asynchronous. The block is called when the connection is finished, i.e. after the call to return.
//Called first
[[LRResty client] get:connectURL
//Called second
return workingDatabases;
//Called later when the connection is finished
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonResponse = [jsonParser objectWithString:[r asString]];
NSDictionary *permittedBases= [jsonResponse objectForKey:#"permittedBases"];
Database *database = [[Database alloc] init];
for (id key in permittedBases) {
/* ... */
[workingDatabases addObject:database];
}
Edit
Ajeet has a valid point too, ensure your array is initialized.
I used the LRResty framework for accessing a RESTful webservice. It was an odd thing anyways, so I switched to a way more rich-featured framework, called "ASIHTTP". I would recommend that to anyone who wants to use RESTful services (and more) on iOS
I asked a question yesterday about a little app that I would like to make for OSX with Cocoa/Obj-C (Xcode).
The princip is easy:
Got an XML file like this one:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample<Description>
</Report>
When the app is opened, there is a window with three text fields.
When a file is loaded (File -> Open) the three text fields get the value of what is in the XML elements. For my example it will be:
TextFields 1 => 20110311TextFields 2 => The TitleTextFields 3 => Description sample
And that's it!
As you can see in my description, it's maybe easy...
But I tried a lot of things, I didn't successed :/
I'm a newbie in Cocoa developpment and there's a lot of dedicated things that I don't understand like how can I make links between CODE & GUI...
Now here is my demand:
If someone could make me an Xcode project similar to my example above, for see what's wrong with my different trys, or explain me how this app can be done (with codes examples)...
I've spend 4 long days on that project but didn't have results :(
Help... :(
Miskia
Two little things to consider:
You should definitely read into the Objective-C / Cocoa documentation.
Otherwise you will never be able to program something yourself.
In the end this will save you lots of time struggling with problems like these.
The things you ask are just the very basics of programming.
(Besides the XML part)
You should never ask people to write complete applications.
People on Stack Overflow are more then willing to help with specific problems,
but they do not work for you.
That being said, here my actual answer:
The XML code you provided contains a syntax error:
The second <Description> should be </Description>
For my example code below I used the following XML file:
<?xml version="1.0" ?>
<Report>
<Date>20110311</Date>
<Title>The Title</Title>
<Description>Description sample</Description>
</Report>
This quickly written example does everything you need.
Create a new application with XCode and open the .....AppDelegate.m file.
Simply paste the Objective-C code mentioned below within the following function:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Paste Here
}
Next click 'Click build and Run'.
Select your file within the NSOpenPanel and click the open-button.
Now you should see a simple dialog with the results.
Hopefully this helps you understand how to parse the XML file.
I can imagine 4 days of struggling must be unpleasant :)
The Objective-C sample code:
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:#"xml",nil];
NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
if(result == NSOKButton){
NSString * input = [openPanel filename];
NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:input] options:0 error:NULL];
NSMutableArray* dates = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* titles = [[NSMutableArray alloc] initWithCapacity:10];
NSMutableArray* descriptions = [[NSMutableArray alloc] initWithCapacity:10];
NSXMLElement* root = [doc rootElement];
NSArray* dateArray = [root nodesForXPath:#"//Date" error:nil];
for(NSXMLElement* xmlElement in dateArray)
[dates addObject:[xmlElement stringValue]];
NSArray* titleArray = [root nodesForXPath:#"//Title" error:nil];
for(NSXMLElement* xmlElement in titleArray)
[titles addObject:[xmlElement stringValue]];
NSArray* descriptionArray = [root nodesForXPath:#"//Description" error:nil];
for(NSXMLElement* xmlElement in descriptionArray)
[descriptions addObject:[xmlElement stringValue]];
NSString * date = [dates objectAtIndex:0];
NSString * title = [titles objectAtIndex:0];
NSString * description = [descriptions objectAtIndex:0];
NSString *output = [NSString stringWithFormat:#"Date: %#\nTitle: %#\nDescription: %#", date, title, description];
NSRunAlertPanel( #"Result", output, #"OK", nil, nil );
[doc release];
[dates release];
[titles release];
[descriptions release];
}
Here some additional information:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/XMLParsing/Articles/UsingParser.html
Sample project:
http://dd5.org/static/XML.zip
How to create a project like above:
- Create new project
- Add code to the header (.h) and implementation (.m) files
- Design the main window
- Finally add the correct bindings
See images below how to add the bindings (already done in the sample project).
Right-click on the App Delegate drag to the NSTextFied (Picture 1).
Release the button and select the correct entry in the ray menu (Picture 2).
Feel free to look at two easy XML parser classes I created.
http://www.memention.com/blog/2009/10/31/The-XML-Runner.html
Source with projects are available at github
https://github.com/epatel/EPXMLParsers
Ok this is a more specific version of my last question.
So on a website there exists some data that is coded in HTML into a table.
In my Cocoa app, I want to download the html code of the website and then read through the html and snag the data from it. I was hoping someone could point out some useful classes/methods for accomplishing the retrieval of the website and putting it into some format where I can read through the code in my program?
Thanks in advance!
Try using hpple, it's an HTML parser for ObjC.
here's an example using it:
#import "TFHpple.h"
NSData *data = [[NSData alloc] initWithContentsOfFile:#"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithHTMLData:data];
//Get all the cells of the 2nd row of the 3rd table
NSArray *elements = [xpathParser search:#"//table[3]/tr[2]/td"];
// Access the first cell
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];