2012-10-06 19 views
10

Sono in perdita qui, ho pensato di provare qualcosa di nuovo con i servizi Web per la mia app.NSURLConnection JSON Invia al server

Non riesco a trascinare i dati senza problemi, ma sto provando a postare sul server e posso solo sembrare che accenda anche questo.

Quello che sto intendendo che accada è il presentare premere il pulsante essere licenziato l'azione:

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

Dopo di che si attraversa:

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

Sono ovviamente manca qualcosa, ma io don' so anche dove guardare. Tutto ciò di cui ho bisogno è un punto nella giusta direzione, ogni aiuto sarebbe grande.

UPDATE

sono stato in grado di ottenere la richiesta al fuoco con il seguente.

Ok sono stato in grado di ottenere la richiesta al fuoco utilizzando il seguente:

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

} 

Ma per qualche motivo il metodo post ha ricevuto solo un mucchio di valori nil, sto ottenendo questo dal lato server. Processing by ProjectsController#create as JSON Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}

UPDATE 2

Con un po 'di lettura da qui: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/

sono stato in grado di vedere se perso la seguente riga. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Quindi il codice di PressSubmit finale è il seguente;

+0

Cosa sta succedendo qui: '[[NSURLConnection alloc] initWithRequest: dataSubmit delegate: self];'? Non stai assegnando la connessione appena inizializzata a una variabile. – FluffulousChimp

+0

Provare a utilizzare NSURLConnection's sendAsynchronousRequest: queue: completionHandler: method. – 8vius

risposta

1

Ho avuto lo stesso problema ma l'ho risolto impostando le opzioni su zero.

Sostituire

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

da

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

Usa opzione per nil se si sta inviando al server JSON, se si sta visualizzando l'uso JSON NSJSONWritingPrettyPrinted.

Spero che questo ti possa aiutare.

Problemi correlati