2012-10-06 15 views
10

Estoy perdido aquí, pensé en probar algo nuevo con los servicios web para mi aplicación.NSURLConnection JSON Enviar al servidor

Puedo bajar datos sin problemas, pero estoy tratando de publicar en el servidor y parece que esto puede incluso disparar.

Lo que estoy con la intención de pasar es el botón de envío de prensa se disparó la acción:

- (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]; 
} 

Después de que se ejecute a través de:

- (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; 
} 

Obviamente estoy perdiendo algo, pero yo no' Ni siquiera sé dónde mirar. Todo lo que necesito es un punto en la dirección correcta, cualquier ayuda sería genial.

ACTUALIZACIÓN

que fue capaz de obtener la solicitud para disparar con lo siguiente.

bien yo era capaz de obtener la solicitud para disparar utilizando la siguiente:

- (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]; 

} 

Pero por alguna razón el método post sólo recibió un montón de valores nulos, me estoy haciendo esto desde el lado del servidor. Processing by ProjectsController#create as JSON Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}

ACTUALIZACIÓN 2

Con un poco de lectura desde aquí: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/

pude ver si se perdió la siguiente línea. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Así que el código final de la versión de envío es el siguiente;

- (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]; 

} 
+0

¿Qué está pasando aquí: '[[NSURLConnection alloc] initWithRequest: dataSubmit delegate: self];'? No está asignando la conexión recién inicializada a una variable. – FluffulousChimp

+0

Intenta usar el método sendAsynchronousRequest: queue: completionHandler: de NSURLConnection. – 8vius

Respuesta

1

Tengo el mismo problema, pero lo resolví estableciendo las opciones a cero.

Reemplazar

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

por opción Usar

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

a nil si va a enviar al servidor JSON, si está mostrando el uso de JSON NSJSONWritingPrettyPrinted.

Espero que esto te ayude.

Cuestiones relacionadas