-4

I need some help with a LoginViewController. Basically I have a small app, and I need to post some data to the app and Im new to POST and JSON. If I can get some help and understanding that would be highly appreciated. Below are some requirements im working with. My .m file is labled as LoginViewController. This is what I have so far

-(void)setRequest {

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

-(void)PostRequest{
    // Create the request.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://dev.apppartner.com/AppPartnerProgrammerTest/scripts/login.php"]];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    // Convert your data and set your request's HTTPBody property
    NSString *stringData = @"some data";
    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
}

I dont know if I'm even setting this up right. I saw many hTTP posts and what not, but im still confused on how I write this syntax and do I need to add anything additional.

I need to:

  1. Send an asynchronous POST request to "some url"
  2. The POST request must contain the parameters 'username' and 'password'
  3. Will receive a JSON response back with a 'code' and a 'message'
  4. Display the parsed code and message in a UIAlert along with how long the api call took in miliseconds
  5. The only valid login is username: Super password: qwerty
  6. When a login is successful, tapping 'OK' on the UIAlert should bring us back to the MainMenuViewController
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Sali
  • 11
  • 1
  • 1
  • Please do not YELL in your titles. – ChiefTwoPencils Aug 23 '15 at 00:41
  • I tried to format your code but for some reason you seem to have all of these methods inside the `setRequest` method. Why? – rmaddy Aug 23 '15 at 00:47
  • 1
    First, you should now use `NSURLSession`, not `NSURLConnection` which is deprecated in the forthcoming iOS 9. Second, what you've got here is pretty close, but the details of how to configure the request depend entirely upon how your web service was written, but I'd be very surprised if you were really sending `application/xml` request. `application/x-www-form-urlencoded` is far more common. Or `text/json`. But we can't help you write the Objective-C code without an understanding of the web service to which you are connecting. That dictates the client-side code. – Rob Aug 23 '15 at 04:27
  • Hey, thanks for the reply. What I'm confused is, im new to ioS, so I just need proper placement of the code. The web service is JSON. I should not have put the xml request parsing part. But if someone can help me construct this, I will run it and see if it works the way the requirements are written. Thanks buches – Sali Aug 23 '15 at 22:18

4 Answers4

2

I'm assuming the methods inside methods are a typo.

Unless you have a particular reason to implement all those delegate methods, you're probably better off using either

NSURLSessionDataTask *task =
[[NSURLSession sharedSession] dataTaskWithRequest:request
                                completionHandler:^(NSData *data,
                                        NSURLResponse *response,
                                        NSError *error) {
    // Code to run when the response completes...
}];
[task resume];

or the equivalent using NSURLConnection's sendAsynchronousRequest:queue:completionHandler: method if you still need to support iOS 6 and earlier and/or OS X v10.8 and earlier.

But the big thing you're missing is the encoding of the request body. To do that, you'll probably want to use URL encoding and specify the appropriate MIME type for that as shown here:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/WorkingwithURLEncoding/WorkingwithURLEncoding.html

Basically, you construct a string by string concatenation in the form "user=ENCODEDUSERNAME&pass=ENCODEDPASSWORD" where the two encoded values are constructed like this:

NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(
    kCFAllocatorDefault,
    (__bridge NSString *)originalString,
    NULL,
    CFSTR(":/?#[]@!$&'()*+,;="),
    kCFStringEncodingUTF8);

Do not be tempted to use stringByAddingPercentEscapesUsingEncoding: and friends. They will do the wrong thing if your strings contain certain reserved URL characters.

dgatwood
  • 10,129
  • 1
  • 28
  • 49
0

I would suggest that you try working with AFNetworking Library.
You can find the code here.
And a very good tutorial here.

0

You can do like that for this.

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
   [request addValue:@"YourUsername" forHTTPHeaderField:@"Username"];
   [request addValue:@"YourPassword" forHTTPHeaderField:@"Password"];

    [NSURLConnection
     sendAsynchronousRequest:request
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

         // TODO: Handle/Manage your response ,Data & errors 

     }];
Piyush
  • 1,534
  • 12
  • 32
0
 -(IBAction)registerclick:(id)sender
{
    if (_password.text==_repassword.text)
    {
        [_errorlbl setHidden:YES];


    NSString *requstUrl=[NSString stringWithFormat:@"http://irtech.com/fresery/index.php?route=api/fresery/registerCustomer"];



    NSString *postString=[NSString stringWithFormat:@"name=asd&email=sooraj&phonenumber=8111&password=soorajsnr&type=1&facebookid=&image_path="];
       // _name.text,_email.text,_mobile.text,_password.text

    NSData *returnData=[[NSData alloc]init];

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:requstUrl]];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[postString length]] forHTTPHeaderField:@"Content-length"];
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];


    returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    resp=[NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];


        c=[[resp valueForKey:@"status" ]objectAtIndex:0];
        b=[[resp valueForKey:@"message"]objectAtIndex:0];