iOS Programming with Web database interface - objective-c

I am programming in Obj-C with X-code and I want to create a project where I am able to pull up information from the database that I have created in my website.
I understand that this can be safely and easily done with a mobile web application. Any ideas how on how I parse the database with Objective-C and X-code ?
Please reply.
Thanks and regards,
-Venkat

If i'm not mistaken the iOS SDK can not connect directly to your database. The way I do this is to send out a post request using the ASIHTTP class and then parse the returned data from your website. Read the documentation here.
This is an example of how to use it from one of my own applications:
NSURL *url = [NSURL URLWithString:#"yoursite.com/page.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:variable1 forKey:#"key1"];
[request setPostValue:variable2 forKey:#"key2"];
[request setPostValue:variable3 forKey:#"key3"];
[request setDelegate:self];
[request startAsynchronous];
You then catch the result with the following code:
- (void)requestFinished:(ASIHTTPRequest *)request {
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
//do your parsing here
}
}
Don't forget to include the required files and classes to your app. But it's all explained in the documentation.
Hope it helps a bit!

Related

How do I POST JSON data object to server iOS8?

I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 8. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
How can I send the below format to server???
{"createFrom":"","createType":"","filename":"AC","filter":"","lstData":[{"FieldName":"LNK_RELATED_CN","FieldValue":""},{"FieldName":"LNK_RELATED_CO","FieldValue":""},{"FieldName":"MLS_PURPOSE","FieldValue":"Inquiry"},{"FieldName":"MLS_STATUS","FieldValue":"Open"},{"FieldName":"MMO_NOTES","FieldValue":""},{"FieldName":"DTE_NEXTACTIONDATE","FieldValue":""},{"FieldName":"MMO_NEXTACTION","FieldValue":""}],"password":"Infodat2","username":"manmeets","IsNew":true}
I have seen code like this:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:#"%#AssetSave",[defaults objectForKey:#"siteAddress"]]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
_responseData = [NSMutableData data];
NSLog(#"request : %#", request);
_nsurlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
But I really don't know how to send a JSON object to a server using a POST method at all. Could anybody please help me out?
The code you have is fine, you just need to create jsonData:
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
(thought you should really also include an &error so you can see what's happening if something goes wrong)

Windows Azure Authentication for Bing Search in Objective-C

On 01.08.12 Bing modified their search api to a Azure, How can I authenticate in Objective-C to use the new bing search api from Azure?
My best guess is to learn from the provided PHP example in the migration word document!! http://go.microsoft.com/fwlink/?LinkID=248077 (Oh god, can't you setup a web page!) or this Java Question - Bing Search API Azure Marketplace Authentication in Java
I'm using ASIHTTPRequest to authenticate with following code.
NSString *queryString = [NSString stringWithFormat:#"'%#'", queryString];
queryString = [queryString urlEncodeUsingEncoding:NSUTF8StringEncoding]; //You'll have to implement url encoding method, preferably in a string category file
NSString *urlString = [NSString stringWithFormat:#"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query=%#&Market='en-US'&$top=50&$format=json", queryString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString] ];
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
[request setUsername:#"YOUR_KEY_HERE"];
[request setPassword:#"YOUR_KEY_HERE"];
[request setDelegate:self];
[request startAsynchronous];
Please note, no appID required. just instead pass your key as username and password. It is successfully getting the data.
However, can't really convert the data to NSString. tried every encoding but can't get the string from the data. Initial googling says it's UTF-8 encoded. But no success.
For above code to work, you must add ASIHTTP framework.
Another thing is, my guess is passing base64 encoded string with this format your_key:yourkey should also work with basic authentication.
I was able to get it to work using just NSUrlConnection. You must first base64encode
NSString *keyString = [NSString stringWithFormat:#"%#:%#", BING_SEARCH_API_KEY, BING_SEARCH_API_KEY];
NSData *plainTextData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
Setup your request
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:searchUrl]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", base64String];
[req setValue:authValue forHTTPHeaderField:#"Authorization"];
Make the request
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
Look at the documentation about how to form searchUrl, and then process data according to the format you specified in $format= (I used json, so mine looks like):
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
I left out error handling, dont forget to add that by checking response as well as error.

Loading stringWithContentsofURL that requires credentials

I am trying to parse an HTML page, but the page requires a username/password to access the data.
How do I pass the credentials to the server so I can load the webpage into my NSData object?
UPDATE for Comments Below
Normally if you are using a web browser, it will pop up a login window for you to type in the credentials. When I execute it in iOS, it doesn't give me anything.
Thanks a lot!
Alan
You can use ASIFormDataRequest. Take a look at it here
NSURL *tempUrl = [NSURL URLWithString:#"http://www.yoursitetoparse.com"];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] init];
request = [ASIFormDataRequest requestWithURL:tempUrl];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setUsername:#"username"]; //Username
[request setPassword:#"password"]; //Password
[request startAsynchronous];
And it's delegate methods:
-(void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"Failed %# with code %d and with userInfo %#",[error domain],[error code],[error userInfo]);
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(#"Finished : %#",[theRequest responseString]);
}

POST with NSURLConnection - NO JSON

I am trying to write an iPhone app in Objective-C. I need to POST data using NSURLConnection. Every example I can find deals with JSON; I do not need to use JSON. All I need to do is POST the data and get a simple 1 or 0 (succeed or fail) from a PHP script. Nothing more.
I came across this code but I am not sure how to use it or modify it to not use JSON:
- (void)performRequest {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://someplace.com/"]];
[request setValue:#"Some Value" forHTTPHeaderField:#"Some-Header"];
[request setHTTPBody:#"{\"add_json\":\"here\"}"];
[request setHTTPMethod:#"POST"];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Fail..
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Request performed.
}
Here's how to create an ordinary post.
First create a request of the right type:
NSURL *URL = [NSURL URLWithString:#"http://example.com/somepath"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
Now format your post data as a URL-encoded string, like this:
NSString *params = #"param1=value1&param2=value2&etc...";
Remember to encode the individual parameters using percent encoding. You can't entirely rely on the NSString stringByAddingPercentEscapesUsingEncoding method for this (google to find out why) but it's a good start.
Now we add the post data to your request:
NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"%i", [data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
And that's it, now just send your request as normal using NSURLConnection (or whatever).
To interpret the response that comes back, see Maudicus's answer.
You can use the following NSURLConnection method if you target ios 2.0 - 4.3 (It seems to be deprecated in ios 5)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString * string = [[NSString alloc] initWithData:data encoding:
NSASCIIStringEncoding];
if (string.intValue == 1) {
} else {
}
}
I've a very similar situation to whitebreadb. I'm not disagreeing with the answers submitted and accepted but would like to post my own as the code provided here didn't work for me (my PHP script reported the submitted parameter as a zero-length string) but I did find this question that helped.
I used this to perform a posting to my PHP script:
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.myphpscriptlocation.net/index.php?userID=%#",self.userID_field.stringValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
NSURLConnection *c = [NSURLConnection connectionWithRequest:request delegate:self];

using JSON-Framework to prepare a json object to post via HTTP Request Objective-C

I am successfully using the json-framework to do GET HttpRequests. Does anyone have code to prepare a json object and do a POST HTTP Request? If so, can you please share some sample objective-c code. Thanks
Take a look at this open source project hosted at google code.
Description:
This framework implements a strict JSON parser and generator in Objective-C.
Download the framework, embed it in your application, and import the JSON.h header. You're now ready to make your application speak JSON. The framework adds categories to existing Objective-C objects for a super-simple interface, and provides classes with more flexible APIs for added control.
Try TwitterHelper.m in Stanford's CS 193P "Presence3Files.zip" package.
I would post the code directly but am unsure if that is cool, license-wise.
USe following code for making a Post Request using JSON Data Object.
self.responseData=[NSMutableData data];
NSURL *url = [NSURL URLWithString:#"http://dev.iworklab.com/myProject/index.php"];
NSString *jsonRequest = [NSString stringWithFormat:#"{\"method\":\"changePassword\",\"customer_id\":\"%#\",\"old_password\":\"%#\",\"new_password\":\"%#\",\"con_password\":\"%#\"}",customerID,oldPasswordText.text,newPasswordText.text,confirmPasswordText.text];
jsonRequest = [NSString stringWithFormat:#"&json_data=%#",jsonRequest];
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: json_data];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [json_data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
passwordConnection = [NSURLConnection connectionWithRequest:request delegate:self];