【问题标题】:NSURLConnection JSON Submit to ServerNSURLConnection JSON 提交到服务器
【发布时间】:2012-10-06 17:21:48
【问题描述】:

我在这里不知所措,我想我应该为我的应用尝试一些新的网络服务。

我可以将数据拉下来没问题,但我正在尝试发布到服务器并且似乎可以让它甚至触发。

我打算在提交按钮上按下动作被触发:

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

我显然错过了一些东西,但我什至不知道去哪里找。我所需要的只是一个正确的方向,任何帮助都会很棒。

更新

我能够使用以下命令触发请求。

好的,我能够使用以下命令触发请求:

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

}

但由于某种原因,post 方法只收到了一堆 nil 值,我是从服务器端获取的。 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];

}

【问题讨论】:

  • 这里发生了什么:[[NSURLConnection alloc] initWithRequest:dataSubmit delegate:self];?您没有将新初始化的连接分配给变量。
  • 尝试使用 NSURLConnection 的 sendAsynchronousRequest:queue:completionHandler: 方法。

标签: ios ruby json nsurlconnection


【解决方案1】:

我遇到了同样的问题,但我通过将选项设置为 nil 解决了它。

替换

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

通过

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

如果您将 json 发送到服务器,请使用 nil 选项,如果您要显示 json,请使用 NSJSONWritingPrettyPrinted

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    相关资源
    最近更新 更多