objective c http query - iphone

Hey, Iam new to objective c and really dont know much about it. I have been given a query that is gonna I need to send data in to the server.Query is like this http://abc.com/insertipademail.php?name=name&email=email I need to enter the name and email I have constructed the string But I dont know how to send it to the server. Can someone help me out please. Or point me in the right direction. Thanks

For starters, take a look a NSString's stringWithContentsOfURL:encoding:error: method. You could do something like:
// NSString * myURLString = whatever you do to build the url
NSURL * myURL = [NSURL URLWithString: myURLString];
NSString * response = [NSString stringWithContentsOfURL: myURL encoding: NSUTF8StringEncoding error: NULL];
NSLog(#"The response was: %#", response);
As written, this will ignore all errors and perform the request synchronously. In a real app, you probably want to handle any error that occur, and perhaps perform the request in the background. See the URL Loading System Programming Guide for further documentation. You can also try using any of several open source libraries such as those suggested in David M.'s answer.

I like the library ASIHTTPRequest. There is also HTTPRiot.

Related

How to store NSData from NSURLConnection sendSynchronousRequest as a pdf file to documents directory in iOS?

I am getting the NSData using
NSData * responseData = [NSURLConnection sendSynchronousRequest:mutableUrlRequest returningResponse:nil error:nil];
How to store this as a PDF to local documents directory? My service is in java which returns byte array.
Thanks !
try like this
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
[data writeToFile:[docPath stringByAppendingPathComponent:#"name.pdf"]
atomically:YES];
You really need to confirm that your request has been successful:
Provide a pointer for the response which on return contains the status code and the MIME type of the response data, possibly also content length and other useful info. Check against what you expect.
Provide a NSError pointer, too in order to get the error when the connection fails (returns nil).
That's what you should always do when you make a toy app. When you make a more serious app, you should use the asynchronous style to perform a network request. Basically, you implement the two NSURLConnection Delegate protocols. There is lot of info already in SO how to accomplish this, and as well in Apple samples. If you have any specific questions, please ask again :)
How to store this as a PDF to local documents directory?
This question has been answered already.

Decode REST Url in Objective-C

I'm creating a module that receive and REST URL and need to match a pattern and extract the parameters
For example:
the URL "http://Product/1" should match the pattern "http://Product/{productId:long}"
and return the Dictionary with productId as a key and "1" as the value in as long
Does anyone knows about a Framework for IPhone that does it, or at least some of it?
NSURL has a method pathComponents, which returns an array with all the different path components. That should help you get the integer part. To get the name I'd use the host method of the NSURL. The docs say, that it should work if the URL is properly formatted, might as well give it a try then.
All in all, no need to convert into a string, there seems to be plenty of methods to work out the components of the URL from the NSURL object itself.
NSString *path = [[#"path+with+spaces"
stringByReplacingOccurrencesOfString:#"+" withString:#" "]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

How to fetch web service response as a string in iPhone?

I've webservice which converts CelsiusToFahrenheit. This webservice response is in string format instead of xml so how can I display a response in a label programmatically?
Is there a sample available for that?
The simplest method is a one-liner:
NSError *error = nil;
myLabel.text = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
As with most one-line solutions, there's a caveat. This method blocks the current thread until the request completes or fails, so you'd better use it in conjunction with performSelectorInBackground:withObject: to avoid locking UI.
Here is a tutorial that I used to retrieve data from a web service using the requestWithURL method of NSURLRequest:
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/
The example is for JSON, but you can just omit all of the JSON stuff from the tutorial, since the string response is going to be fed into your connectionDidFinishLoading method.

How to uniquely identify nsmangedobject with string?

I'm using Core data and region monitoring. The only way to distinguish between monitored regions is with a NSString for identifier. I'd love to use NSManagedObjectID, but I can't get it to work.
What I've tried:
NSURL *objURL = [managedObjectID URIRepresentation];
NSError *err;
NSString *identifier = [NSString stringWithContentsOfURL:myURL
encoding:NSASCIIStringEncoding
error:&err];
the error I get is:
The operation couldn’t be completed. (Cocoa error 256.)
Any ideas of a better way? Or what I'm doing wrong?
You should not get the contents of the URI of the NSManagedObjectID. stringWithContentsOfURL:encoding:error: tries to load the resource pointed by the URI; it uses appropriate operations depending whether the URI is http or file or etc. But it doesn't know how to deal with an NSManagedObjectID URI, and it's not what you want to do anyway.
Instead, I guess what you want to do is
NSString*identifier=[objURL absoluteString];
This gives a string representation of the URL.
I'll add Marcus's comment so that everyone will notice:
Be aware that the objectID can and does change, especially when a migration occurs. Do not rely on that value to be consistent between one launch of the application and the next.

Creating a highscore like system, iPhone side

I'm sorry for opening a new question, I had to - as I wrote the other question from my iPhone as unregistered user and it is not very comfortable to write from the iPhone.
Rephrasing the question:
Is it possible to use the:
[NSMutableArray writeToURL:(NSString *)path atomically:(BOOL)AuxSomething];
In order to send a file (NSMutableArray) XML file to a url, and update the url to contain that file?
for example:
I have an array and I want to upload it to a specific URL and the next time the app launches I want to download that array.
NSMutableArray *arrayToWrite = [[NSMutableArray alloc] initWithObjects:#"One",#"Two",nil];
[arrayToWrite writeToURL:
[NSURL urlWithString:#"mywebsite.atwebpages.com/myArray.plist"] atomically:YES];
And at runtime:
NSMutableArray *arrayToRead =
[[NSMutableArray alloc] initWithContentsOfURL:[NSURL urlWithString:#"mywebsite.atwebpages.com/myArray.plist"]];
Meaning, I want to write an NSMutableArray to a URL, which is on a web hosting service (e.g. batcave.net), the URL receives the information and updates server sided files accordingly.
A highscore like setup, user sends his scores, the server updates it's files, other users download the highscores at runtime.
I hope this is clarified.
Edit: What I am looking for is scripting PHP or ASP so the website, the URL where the data is sent to would know how to handle it. I want an example or a tutorial on how to implement this scripting for handling data, if it's possible to do this on a web hosting service.
~Thanks in advance.
To answer the question "How do I create a high score like system?", there are multiple parts of the system:
You need an ID for each user (a GUID generated on the iPhone, together with the users name should be sufficient).
You need a server that: remembers high scores; receives high scores from users; either displays (on a web site) the high scores and/or makes the high scores available for download to the phone.
You need some fraud protection, although that is likely fighting a losing battle against jailbreakers.
On the iPhone app side, you might want to be able to download the current high scores for display, which is done easily enough with something like:
int statusCode = 0;
NSData* result = nil;
NSHTTPURLResponse* response = nil;
NSError* error = nil;
NSString* url = #"http://www.yourserver.com/highscores.php"; // returns XML plist data
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:180];
result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// NSLog( #"NSURLConnection result %d %# %#", [response statusCode], [request description], [error description] );
statusCode = [response statusCode];
if ( (statusCode == 0) || (!result && statusCode == 200) ) {
statusCode = 500;
}
Since it is synchronous, you might want to put it inside an NSOperation. Alternatively, you can use
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate
To send high score data, because it is so small, the easiest way is simply to encode it in the URL.
NSString* url = [NSString stringWithFormat:#"http://www.yourserver.com/sethighscores.php?uid=%#;name=%#;score=%d;antifraud=%#", [uid encodeParameter], [name encodeParameter], score, [secureHash encodeParameter]];
Where encodeParameter is a custom category on NSString that encodes URL parameters and secureHash is a string representing a one way secure hashing of the uid, name, score and some secret known to your iPhone app and your web site. You'll need to figure these out on your own or ask separate questions since this is already getting long.
According to NSData writeToURL docs (at least for iPhone OS 2.2.1):
"Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:atomically:, except for the type of the first argument."
Although the docs for NSArray/NSDictionary/NSString do not specifically mention the restriction, it would seem highly likely that the same restriction applies.
So you will have to upload the XML using some other mechanism.
Also, web sites generally are read only, unless you provide specific code on the web server to support uploading.