Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLConnection JSON Submit to Server

I am at a loss here, I thought I'd try something new with web services for my app.

I can pull data down no problem, but I am trying to post to the server and just can seem to get this to even fire.

What I am intending to happen is on submit button press the action be fired:

- (IBAction)didPressSubmit:(id)sender {

     //JSON SERIALIZATION OF DATA
     NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    [projectDictionary setObject:[projectName text] forKey:@"name"];
    [projectDictionary setObject:[projectDescShort text] forKey:@"desc_short"];
    [projectDictionary setObject:[projectDescLong text] forKey:@"desc_long"];

    NSError *jsonSerializationError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];

    if(!jsonSerializationError) {
        NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"Serialized JSON: %@", serJSON);
    } else {
        NSLog(@"JSON Encoding Failed: %@", [jsonSerializationError localizedDescription]);
    }

    // JSON POST TO SERVER
    NSURL *projectsUrl = [NSURL    URLWithString:@"http://70.75.66.136:3000/projects.json"];
    NSMutableURLRequest *dataSubmit = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    [dataSubmit setHTTPMethod:@"POST"]; // 1
    [dataSubmit setValue:@"application/json" forHTTPHeaderField:@"Accept"]; // 2
    [dataSubmit setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; // 3
    [dataSubmit setHTTPBody: jsonData];

     [[NSURLConnection alloc] initWithRequest:dataSubmit delegate:self];
}

After that it runs through:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"DidReceiveResponse");

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    NSLog(@"DidReceiveData");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"BLAH CHECK YOUR NETWORK" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

I am obviously missing something, but I don't even know where to look. All I need is a point in the right direction, any help would be great.

UPDATE

I was able to get the request to fire with the following.

Okay I was able to get the request to fire using the following:

- (IBAction)didPressSubmit:(id)sender {


    NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    [projectDictionary setObject:[projectName text] forKey:@"name"];
    [projectDictionary setObject:[projectDescShort text] forKey:@"desc_small"];
    [projectDictionary setObject:[projectDescLong text] forKey:@"desc_long"];

    NSError *jsonSerializationError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];

    if(!jsonSerializationError) {
        NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"Serialized JSON: %@", serJSON);
    } else {
        NSLog(@"JSON Encoding Failed: %@", [jsonSerializationError localizedDescription]);
    }

    NSURL *projectsUrl = [NSURL URLWithString:@"http://70.75.66.136:3000/projects.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    [request setHTTPMethod:@"POST"]; // 1
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; // 2
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; // 3
    [request setHTTPBody: jsonData]; // 4


    (void) [[NSURLConnection alloc] initWithRequest:request delegate:self];

}

But for some reason the post method only received a bunch of nil values, I am getting this from the server side. Processing by ProjectsController#create as JSON Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}

UPDATE 2

With a little read from here: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/

I was able to see if missed the following line. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

So final didPressSubmit code is as follows;

- (IBAction)didPressSubmit:(id)sender {


    NSMutableDictionary *projectDictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    [projectDictionary setObject:[projectName text] forKey:@"name"];
    [projectDictionary setObject:[projectDescShort text] forKey:@"desc_small"];
    [projectDictionary setObject:[projectDescLong text] forKey:@"desc_long"];

    NSError *jsonSerializationError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];

    if(!jsonSerializationError) {
        NSString *serJSON = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"Serialized JSON: %@", serJSON);
    } else {
        NSLog(@"JSON Encoding Failed: %@", [jsonSerializationError localizedDescription]);
    }

    NSURL *projectsUrl = [NSURL URLWithString:@"http://70.75.66.136:3000/projects.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:projectsUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    [request setHTTPMethod:@"POST"]; // 1
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; // 2
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"]; // 3
    [request setHTTPBody: jsonData]; // 4


    (void) [[NSURLConnection alloc] initWithRequest:request delegate:self];

}
like image 332
Richard D Walsh Avatar asked Oct 06 '12 17:10

Richard D Walsh


1 Answers

I got same issue but I resolved it by setting the options to nil.

Replace

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];

by

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:projectDictionary options:nil error:&jsonSerializationError];

Use option to nil if you are sending json to server, if you are displaying json use NSJSONWritingPrettyPrinted.

Hope this will help you.

like image 181
Midhun MP Avatar answered Oct 29 '22 15:10

Midhun MP