RedShirt
RedShirt

Reputation: 864

Sending post request IOS 7

Okay I have been trying to adapt to objective C and it has been a roller coaster for me, anyways I am just trying to send a simple post request to a server, however it doesn't look as simple as it was for android. Currently I have the following method:

-(void)postMethod
{

    [self.connection cancel];

    //initialize new mutable data
    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;

    //initialize url that is going to be fetched.
    NSURL *url = [NSURL URLWithString:@"http://blank.com/register.php"];

    //initialize a request from url
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method
    [request setHTTPMethod:@"POST"];
    //initialize a post data
    NSString *postData = @"username=postTest&displayname=testingPoster&password=postest&passwordc=postest&email=posttesting%40posttest.com&bio=I+am+tesring+the+post+test&skills=I+am+a+hacka&interests=hacing+and+cracking&skills_needed=some+php+skills&company=Post+testing+the+script&dob=naaaaaa&occupation=Qoekkk";
    //Here you can give your parameters value

    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //set post data of request
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //initialize a connection from request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.connection = connection;


    //start the connection
    [connection start];
}

and I have a button to call the function:

- (IBAction)register:(id)sender {

    [self postMethod];


}

I did make sure I included the NSURLConnectionDataDelegate in my header file, however when I try to send the request when I click the button, it doesn't go through and it just stops the program, it doesn't any error. Any suggestions, I have been searching all over the net just to learn how to send a post request, I don't think it should be very difficult.

And just incase it matters, I am using the latest iphone sdk for ios 7.

Upvotes: 2

Views: 7212

Answers (2)

Ivica M.
Ivica M.

Reputation: 4823

Note that for iOS 7 NSURLSession is the recommended way to go. NSURLConnection will probably be deprecated in future releases. You can make your POST request using either of the three types of URL session tasks. NSURLSessionDataTask is pretty much equivalent to NSURLConnection. NSURLSessionUploadTask and NSURLSessionDownloadTask (which writes received data to the disk) can be used in a background session and continue (in another process) even if your application gets suspended or crashes. More can be read in this guide.

Upvotes: 3

HungryArthur
HungryArthur

Reputation: 1087

AFNetworking is tried and tested. - check out the example below which also uses basic authentication:

- (void)postToAPI   {

    NSURL *postURL = [NSURL URLWithString:@"http://yourdomain.com/api/operation"];

    AFHTTPClient* httpClient = [AFHTTPClient clientWithBaseURL:postURL];
    httpClient.parameterEncoding = AFJSONParameterEncoding;
    [httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [httpClient setDefaultHeader:@"Accept" value:@"application/json"];

    // Set up authentication - Get username from keychain
    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"bnmcred" accessGroup:nil];
    NSString *password = [keychainItem objectForKey:(__bridge id)kSecValueData];
    NSString *username = [keychainItem objectForKey:(__bridge id)kSecAttrAccount];

    [httpClient setAuthorizationHeaderWithUsername:username password:password];

    // Create Post Dictionary
    NSMutableDictionary* postRequestDictionary = [[NSMutableDictionary alloc] init];
    postRequestDictionary[@"your_post_item_1"] = @"Hello";
    postRequestDictionary[@"your_post_item_2"] = @"World";

    // Create Request
    NSMutableURLRequest* request = [httpClient requestWithMethod:@"POST" path:nil parameters:postRequestDictionary];

    self.httpOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@"Success");

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Failure with error:%@", error);
    }];

    [self.httpOperation start];
}

Upvotes: 1

Related Questions