POST JSON data from iOS to mssql Server [closed] - ios

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Can someone please tell me what is the best way to create web service that sends JSON to MS SQL server.(php or .net POST web service?)
I want to host the web service on IIS if possible.Links of tutorials will be very useful.
Many Thanks.

//Create the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"your script name.php"]];
// create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server
NSString *userUpdate =[NSString stringWithFormat:#"artist_email=%# ",your string Name,nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}

I would recommend using ASP.NET Web API it supports both JSON and XML out of the box and the development is relatively easy as you don't have to manage the parsing of JSON data to and from C# objects, you can then just use Entity Framework to communicate with the database.
Start with : http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
And: http://www.entityframeworktutorial.net/EntityFramework4.3/Introduction.aspx I think this is a bit out dated but the core will remain the same

Related

Using NSURLSession to POST, what is the correct way to post the variables?

I am following this tutorial: http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service. Trying to set up a basic web service. Seems like the tutorial is old material and ASIHTTPRequest is no longer continued. I have been trying to use NSURLRequest instead. First question, is NSURLRequest a pretty standard way to be doing this? I just want something for basic GET, POST etc, should I be doing it a different way?
My code is:
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
NSLog(#"We want to unlock for the code %#",self.textField.text);
//Get a device ID, (actually can't do this aymore)
NSString *uniqueIdentifier = #"My iPhone";
NSString *code = self.textField.text;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.madasd.co/promos/"]];
request.HTTPMethod=#"POST";
//Set the header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString *myString = [NSString stringWithFormat:#"rw_app_id=1&code=%#&device_id=%#",code,uniqueIdentifier];
NSLog(#"%#",myString);
NSData *requestBodyData = [myString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody=requestBodyData;
//Create url and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn start];
return TRUE;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
}
Second question, I have tested the backend using curl so I know it works fine, however the response I get is "Invalid Request", I think this is because the string I am sending is not correct. Am I doing this correct using the var names and & operators? Any pointers on this would be great! thanks. (Running a LAMP server on Linode!)
EDIT:
Also tried sending as JSON:
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSDictionary *mapData = [[NSDictionary alloc]initWithObjectsAndKeys:#"1",#"rw_app_id",code,#"code",uniqueIdentifier,#"device_id", nil];
NSError *error = nil;
NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
request.HTTPBody=requestBodyData;
Still getting the same error.
A couple of thoughts:
Don't use NSURLConnection. It is deprecated as of iOS 9. Use NSURLSession. See Using NSURLSession in the URL Loading System Programming Guide.
Decide what type of request you need to prepare. You specified application/xml in your header, but are creating a application/x-www-form-urlencoded request. Your Content-Type header must match how you're building the HTTPBody.
What type of request does your server require? x-www-form-urlencoded? XML? JSON?
Also, what type of response does your server provide?
If building a application/x-www-form-urlencoded request (as suggested by the body of your request), you are not properly percent escaping the values (see https://stackoverflow.com/a/20398755/1271826).
If you use delegate based NSURLConnection or NSURLSession, you should not just grab the results in didReceiveData. What you need to do is
Instantiate a NSMutableData before starting the request;
Have didReceiveData merely append to that NSMutableData;
Only when connectionDidFinishLoading: (in NSURLConnection) or URLSession:task:didCompleteWithError: (in NSURLSession) is called, should you then use the NSMutableData.
Alternatively, if using the block-based NSURLSession, this concern is completely eliminated (since you're not implementing any delegate methods). Using completionHandler-based methods of NSURLSession is much easier.
If all of this is too complicated, you might consider using AFNetworking's AFHTTPSessionManager (but not AFHTTPRequestOperationManager) to build your requests. It gets you out of the weeds of properly building requests, implementing delegate methods, etc.
You might need to wrap the strings into a dictionary and get the NSData object from a call to NSJSONSerialization. Though it depends on the form expected by the server.

How do I figure out when the contents of NSData indicate that a webservice request has failed?

I'm trying to persist data from a microsoft web service call to a file when my app starts up. If the app is able to complete the webservice request, it's storing the data in an NSData object. Assuming the data has been successfully requested and stored, I want to execute certain code that I would NOT want to if the webservice is unsuccessful.
My webservice request is as follows:
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc]init];
[request1 setURL:[NSURL URLWithString:#"---URL---"]];
[request1 setHTTPMethod:#"GET"];
NSURLResponse *request1Response;
NSData *request1Handler = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&request1Response error:nil];
NSString *request1Reply = [[NSString alloc]initWithBytes:[request1Handler bytes] length:[request1Handler length] encoding:NSASCIIStringEncoding];
NSData *data1 = [request1Reply dataUsingEncoding:NSUTF16StringEncoding];
So basically, the response is dropped into that data1 object.
When connected to the internet, the request executes fine. The code that follows is wrapped in a if(data1){ conditional to make sure that the webservice request is successful before executing it. The problem is that when I disconnect from the internet(and cut off access to that webservice), the code inside the conditional is still being executed.
I tried comparing data1 to nil, logging data1 to do a direct comparison of the contents, etc, but I gather that that data1 object isn't nil; it probably contains some sort of failure message that I have thus far been unable to access. What can I do in the conditional or in the webservice request itself to figure out when the request fails?
Create an NSError object and pass it as argument to the sendSynchronousRequest: method, then if there is network or another error, the err object will populated with error information hence it will not be nil. That means you can check if(!err)contiune else there is an error
check the code:
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc]init];
[request1 setURL:[NSURL URLWithString:#"http://www.google.com"]];
[request1 setHTTPMethod:#"GET"];
//object where error will be saved
NSError *err;
NSURLResponse *request1Response;
NSData *request1Handler = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&request1Response error:&err];//pass the err here by reference
NSString *request1Reply = [[NSString alloc]initWithBytes:[request1Handler bytes] length:[request1Handler length] encoding:NSASCIIStringEncoding];
NSData *data1 = [request1Reply dataUsingEncoding:NSUTF16StringEncoding];
and then you can check here:
if (err){
NSLog(#"error: %#", err);
}
You should at least be checking for an error response by populating the error pointer parameter.
Ideally you should be using a different API which gives you access to more details such as the response HTTP status code which you should be using to determine what happened even if you did get something which looks like success.

Showing PhpMyAdmin database in iOS uitableview

I am creating a app in which I want to fetch data from PhpMyAdmin database to my UITableView.
Is there any good tutorial for this purpose? Please not any chat app tutorials I simply want to display my table in tableview.
My table has 5 fields (id, fname, lname, email, address).
Thank you
The best way to handle it is to create a JSON API for your database and then make your iOS app parse the JSON data.
Here is an example of how to create a JSON output from MySQL using PHP.
When you have your JSON output you should download it from the app using the NSURLConnectionand NSJSONSerialization, something like this:
NSURL* url = [NSURL urlWithString:#"http://yourapi.url/here"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError **error = nil;
NSData *data = [[NSData alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]];
NSInteger httpStatus = [((NSHTTPURLResponse *)response) statusCode];
NSLog(#"responsecode:%d", httpStatus);
NSDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorInfo];
The content of your JSON will be placed in the parsedJson dictionary.
This is just a quick example of using a synchronous request with NSURLConnection. If you want a asynchronous solution you should read the documentation on NSURLConnection.
To show the data in a UITableView you should checkout this tutorial.

retriving JSON from a url using objective C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to objectiveC,
I have a problem in retrieving JSON type from a url, the url represent a web service which had built to return both JSON and XML, when I tried to consume the web service from the url the result was XML,
what I need is to determine the type of returning data to be JSON in the request.
by the way I am sure that the web service return both XML and JSON.
and here is my code where I get XML:
NSURL *url = [[NSURL alloc] initWithString:#"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSString *result=[[NSString alloc] initWithContentsOfURL:url];
NSLog(#"%#",result);
the result is :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<restaurantImpls>
<Resstaurant Name="Abo Alshamat" PhoneNumber="0991992994" MobileNumber="0991992993" LastName="Shame" ID="1" FirstName="Samer"/>
<Resstaurant Name="AL-Kamal" PhoneNumber="0992993995" MobileNumber="0992993994" LastName="Ali" ID="2" FirstName="Ahmad"/>
<Resstaurant Name="Abo-MAhmoud" MobileNumber="0993377800" ID="12"/>
<Resstaurant Name="Four Season" PhoneNumber="0993994996" MobileNumber="0993994995" LastName="Ammar" ID="3" FirstName="William"/>
<Resstaurant Name="uuuuu" MobileNumber="0999555777" LastName="William" ID="20" FirstName="Ammar"/>
<Resstaurant Name="NewOneFromI2" MobileNumber="0999888777" ID="18"/>
<Resstaurant Name="JOURY" PhoneNumber="0999999998" MobileNumber="0999998997" ID="4"/>
<Resstaurant Name="TestTestRestaurant,Ammar,Hamed" MobileNumber="202020" ID="19"/>
</restaurantImpls>
thank you for your time.
We couldnt set the response data type from our request. Response is set from the server. From your description(web service return both XML and JSON), my guess is you need to post a status variable which showing the return status like isXML. It's only my guess. You need to contact server side programmers about the implementation of this request.
EDIT
Try below code
responseData = [[NSMutableData alloc]init];
NSURL *url = [[NSURL alloc] initWithString:#"http://192.168.1.1:8080/test2/eattel/restaurants"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/json" forHTTPHeaderField:#"accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
(void)[NSURLConnection connectionWithRequest:req delegate:self];
Then You need to implement NSURLConnection Delegates.
#pragma mark - NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
}

iOS Networking Library Suggestion [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 months ago.
Improve this question
I would some suggestion about the choose of an iOS networking library for my app.
My needs are:
Send asynchronous request (GET and POST) and if the network is down display a UIAlertView to inform the user of the error.
Send simple synchronous request (GET) and if the network is down do the same of the above point.
Does anyone have some lib to suggest? (except ASIHTTPRequest that is no longer supported) Possibly, if this lib have some nice doc is better. I'm an iOS beginner.
Thanks for help in advance.
I've heard good things about RestKit https://github.com/RestKit/RestKit
There is a good list of alternatives at the bottom of this blog post. http://allseeing-i.com/[request_release];
I've only used ASIHTTPRequest before, and even though it's not longer being developed by Ben Copsey, it looks like he's still merging pull requests and stuff. It's in use by so many people, I wouldn't be surprised if the community picks it up. It will probably be safe for at least another version of iOS.
You don't really need a library for this.
To send a synchronous GET request:
//set up the GET URL and params
NSURL *getURL = [NSURL URLWithString:#"http://somesite.com/somepath?foo=bar"];
//create the request
NSURLRequest *request = [NSURLRequest requestWithURL:getURL];
//get the response
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
To send a synchronous POST request:
//set up the POST URL and params
NSURL *postURL = [NSURL URLWithString:#"http://somesite.com/somepath"];
NSString *postParams = #"foo=bar&hello=world";
//create the request - this bit is the same for every post
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:postURL];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *data = [postParams dataUsingEncoding:NSUTF8StringEncoding];
[self addValue:[NSString stringWithFormat:#"%i", [data length]] forHTTPHeaderField:#"Content-Length"];
[self setHTTPBody:data];
//get the response
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
In either case if responseData is nil or error is not nil, present an alert using the following:
[[[[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease] show];
As stated in the question he is also looking for asynchronous requests.
I would suggest AFNetworking or GCNetworkKit (the last one is my own). Both libraries are very easy to use and yet powerful.
I don't think AFNetworking provides a synchronous network request though. Well at least mine doesn't. You shouldn't do that anyway.
Both libraries support error handling. There should be no problem on implementing an UIAlertView.
You can find them on GitHub. Just search for them. Hope this helps :)

Resources