7

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 5. 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:

    //build an info object and convert to json
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];

    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:someURLSetBefore];
    [request setHTTPMethod:@"POST"];
    // any other things to set in request? or working this way?

    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    // What to do with NSURLConnection? Or how to send differently?

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?

Chisx
  • 1,976
  • 4
  • 25
  • 53
CGee
  • 1,650
  • 5
  • 20
  • 31

4 Answers4

16

I worked it out by trying a bit around, here's my code:

    //build an info object and convert to json
    NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, @"name", language, @"language", nil];

    //convert object to data
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:someURLSetBefore];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:jsonData];

    // print json:
    NSLog(@"JSON summary: %@", [[NSString alloc] initWithData:jsonData
                                                     encoding:NSUTF8StringEncoding]);
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
CGee
  • 1,650
  • 5
  • 20
  • 31
  • Could you possibly elaborate on what is happening in your code? I have used it in my own app now, but I honestly don't know that much about what it's doing. I understand the dictionary and turning it into data for JSON, but everything with the URLRequest and the URLConnection is unknown for me. Any clarification would be great! – BlueBear Sep 04 '13 at 17:37
  • 1
    An NSURLRequest is basically an object to set the properties of your web fetch. In normal fetches you would have the most used defaults set automatically, but as I want to send data I want to use the HTTP POST method and cause I want to receive a JSON object I'm telling the server this by setting the Content-Type and Accept HTTP header fields to JSON format. To learn more about the HTTP protocol and especially the HTTP header just search for them or read here http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol and here http://en.wikipedia.org/wiki/List_of_HTTP_header_fields. – CGee Sep 05 '13 at 12:36
  • To learn more about NSURLConnection I think the best way is to just read its class reference in Apples Documentation here https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html. In general I can only encourage you to first have a look into Apples documentation first, as it is a great (and definitely up-to-date) source for learning these things. – CGee Sep 05 '13 at 12:41
  • Oh, of course I meant that I want to *send* a JSON object, not receive. The editing time's over already ... :( – CGee Sep 05 '13 at 12:44
  • @CGee For the error:&error do you just declare a NSError and set it to nil above? Because I tried that and its just crashes?? – Supertecnoboff Apr 16 '14 at 09:12
2
- (IBAction)txtFetchData2:(id)sender {
NSString *queryString = [NSString stringWithFormat:@"http://example.com/username.php?name=%@", [self.txtName text]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
                          requestWithURL:[NSURL URLWithString:
                                          queryString]
                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                          timeoutInterval:60.0];
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                @"Value1", @"Key1",
                                @"Value2", @"Key2",
                                nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
                       options:NSJSONWritingPrettyPrinted error:&error];
[theRequest setHTTPMethod:@"POST"];
[theRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// should check for and handle errors here but we aren't
[theRequest setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if (error) {
        //do something with error
    } else {
        NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
        NSLog(@"Response: %@", responseText);

        NSString *newLineStr = @"\n";
        responseText = [responseText stringByReplacingOccurrencesOfString:@"<br />" withString:newLineStr];            
        [self.lblData setText:responseText];
    }
}];
}
CoderPi
  • 12,985
  • 4
  • 34
  • 62
Mannam Brahmam
  • 2,225
  • 2
  • 24
  • 36
1

NSString *strUrl = @"URL"; NSURL *url = [NSURL URLWithString:strUrl];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];

// For set postdata in string
NSString *strPatientID = [NSString stringWithFormat:@"%@%@%@%@",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text];
NSString *deviceToken = @"";
postString = [NSString stringWithFormat:@"practiceid=%@&email=%@&password=%@&devicetoken=%@",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken];


NSMutableData *httpDataBody = [NSMutableData data];
[httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSString *strPostLength = [NSString stringWithFormat:@"%lu",[httpDataBody length]];

if ([httpDataBody length ] > 0){

    [request addValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request addValue:strPostLength forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:httpDataBody];

}

urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[urlConnection start];
0
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://webstar52.com/demo/webcommunity/work.php"]]];
    NSString *post = [NSString stringWithFormat:@"&tag=%@&user_id=%@",@"getcontact",@"10408"]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    [request setHTTPMethod:@"POST"];      
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];
  conn  = [[NSURLConnection alloc]initWithRequest:request delegate:self];
Tirth
  • 7,801
  • 9
  • 55
  • 88
Dipak
  • 2,263
  • 1
  • 21
  • 27