0

I have a pretty basic internal iOS app that I want to send a POST to a web-server. You basically have a bunch of buttons, and depending on what button you press, it sends a pre-defined "message" to the web-server.

Once the buttons are pressed it takes them to another view and says Thanks for selecting the button that you pressed. I also want a pre-defined message to be sent to a web-server, formatted and then emailed to a static email address.

This is what I have so far.. I'm just trying to figure out the best way to send the POST. Is the way I have setup the best way to do it? Or is there smarter way to do this?

Sorry if it's messy and un-organized.. I'm very new to iOS development.

@interface DrinkViewController () {
NSString *buttonlabel;
NSString *urlEncodeUsingEncoding;
}
@end

@implementation DrinkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

-(IBAction)selectButton:(id)sender{
    NSLog(@"Button Pressed:%d",((UIButton *)sender).tag);
    NSString *dvalue;
    switch (((UIButton *)sender).tag) {
        case 1:
            dvalue = @"Button 1";
            break;
        case 2:
            dvalue = @"Button 2";
            break;
        case 3:
            dvalue = @"Button 3";
            break;
        case 4:
            dvalue = @"Button 4";
            break;
        case 5:
            dvalue = @"Button 5";
            break;
        case 6:
            dvalue = @"Button 6";
            break;
        case 7:
            dvalue = @"Button 7";
            break;

    }
    buttonlabel = dvalue;

    [self performSegueWithIdentifier:@"selectionTransition" sender:sender];


    NSData *postData = [buttonlabel dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request =  [NSMutableURLRequest alloc];
                                    [request setURL:[NSURL URLWithString:@"http://www.abc.com/form.php"]];
                                    [request setHTTPMethod:@"POST"];
                                    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                                    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                                    [request setHTTPBody:postData];
    NSLog(@"POST: %@ sent to %@", buttonlabel, request);
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"selectionTransition"]) {

        NSLog(@"%@", buttonlabel);
        // Get destination view
        DetailViewController *vc = [segue destinationViewController];

        // Pass the information to your destination view
        [vc setLabelValue:buttonlabel];
    }
}

@end
Ben T.
  • 39
  • 1
  • 5

4 Answers4

1

Here's what you need to use: NSURLRequest, NSURLConnection, NSURLResponse, NSURL. You might use another library, but i would recommend you to try to understand how these classes work (since you are new to this).

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsurlconnection_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

Here's how it works: You use the server url, create a NSURLRequest, assign the proper HTTP method(POST, GET, etc) and other necessary request headers, then you would call on NSURLConnection to get the response and the server data.

J2theC
  • 4,412
  • 1
  • 12
  • 14
0

My suggestion would be to use a 3rd party library. It will simplify the process for your considerably and save you a lot of time. I usually use the AFNetworking library.

https://github.com/AFNetworking/AFNetworking

There is a POST example here:

http://www.6foot3foot.com/developer-journal/afnetworking-php

ezekielDFM
  • 1,947
  • 13
  • 26
0

Check out this post. I wrote a NetworkClient class that uses AFNetworking (my fav 3rd party library). This is pretty flexible and feel free to modify it to fit your needs.

Community
  • 1
  • 1
LJ Wilson
  • 14,445
  • 5
  • 38
  • 62
0

I am by far no expert, but I do make network calls in my code. I chose MKNetworkKit to replace my sorry network code.

Here is an example of how you may use it in your project:

- (void)myFunctionToSendDataToTheServer
{
    /*
     *  So here is a basic idea of how you could quickly use MKNetworkKit.
     *  the [op addData:postData forKey:@"postDataKey"]; call is where you're
     *  add that post data to the request body.
     */
    NSString *someVariableYouWantPosted;
    NSData *postData = [someVariableYouWantPosted dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:@"abc.com"];

    MKNetworkOperation *op = [engine operationWithPath:@"/form.php"];
    [op addData:postData forKey:@"postDataKey"];

    /*
     *  If you're not familiar with blocks then this "onCompletion^" might look weird.
     *  Inside of the curly braces will get called when the request is done.
     */

    [op onCompletion:^(MKNetworkOperation *completedOperation) {
        NSLog(@"Successful response from server: %@", [completedOperation responseString]);

        /*
         *  There are also some nice helper methods for extracting the response data in a different form
         *  [completedOperation responseJSON];
         *  [completedOperation responseImage];
         *  [completedOperation responseData];
         */

    } onError:^(NSError *error) {
        if ([error code] == kCFURLErrorNotConnectedToInternet) {
            /*
             *  Maybe retry? 
             *  This network kit also comes with a "freezable" property on the MKNetworkOperation.
             *  If you set that to YES then you don't need to worry about internet connectivity,
             *  the kit will try to send later when it reconnects.
             */
        }
        else {
            /*
             *  You'll have your work cut out for you here. Sourcing the problem can be difficult.
             *  Simply an alert message or loggin the NSError to find out where you went wrong.
             */
        }

    }];

    /*
     * Don't forget to call "enqueueOperation:".
     *  This actually gets the request going and sends it off to the server.
     */

    [engine enqueueOperation:op];
}

Let me know if you have any other questions regarding this topic or if I wasn't clear.

Thawe
  • 171
  • 6