Подтвердить что ты не робот

NSURLConnection JSON Отправить на сервер

Я в затруднении здесь, я думал, что попробую что-то новое с веб-сервисами для своего приложения.

Я могу вытащить данные без проблем, но я пытаюсь отправить сообщение на сервер и просто может показаться, что это даже срабатывает.

То, что я намереваюсь совершить, находится на кнопке отправки, нажатие на действие:

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

После этого он проходит через:

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

Мне явно чего-то не хватает, но я даже не знаю, где искать. Все, что мне нужно, это точка в правильном направлении, любая помощь будет большой.

UPDATE

Мне удалось отправить запрос на следующее:

Хорошо, мне удалось запустить запрос, используя следующее:

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

}

Но почему-то почтовый метод получил только кучу нулевых значений, я получаю это со стороны сервера. Processing by ProjectsController#create as JSON Parameters: {"{\n \"desc_long\" : \"a\",\n \"name\" : \"a\",\n \"desc_small\" : \"a\"\n}"=>nil}

ОБНОВЛЕНИЕ 2

Немного читайте здесь: http://elusiveapps.com/blog/2011/04/ios-json-post-to-ruby-on-rails/

Я смог увидеть, пропустил ли следующую строку. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

Итак, окончательный код didPressSubmit выглядит следующим образом:

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

}
4b9b3361

Ответ 1

У меня такая же проблема, но я решил ее, установив параметры в nil.

Заменить

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

по

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

Используйте параметр nil, если вы отправляете json на сервер, если вы используете json use NSJSONWritingPrettyPrinted.

Надеюсь, это поможет вам.