1

几天来,我一直在阅读代码示例和帖子,但我还没有找到将 JSON 数据从我的 Core Data 对象发布到 RESTful Web 服务的明确方法。有大量关于从 Web 服务中提取 JSON 的文档,但没有太多关于发回内容的文档。谁能给我指出一个很好的例子或发布一些关于如何做到这一点的代码?我正在使用核心数据,并且我将要发回的对象映射到字典,但我缺少将其发送到服务的代码。

编辑:

我最终得到了下面的代码,它看起来正确并且运行没有错误,但是我返回了 0 字节的数据,并且我的 web 服务似乎没有收到请求。JSON 数据看起来不错,URL 是正确的,我可以点击 web 服务并从中获取 JSON 数据。NSURLConnection 委托方法也会按预期触发。

下面有什么我遗漏的吗?

- (void)SubmitSystems
{
    NSFetchRequest * allSystems = [[NSFetchRequest alloc] init];
    [allSystems setEntity:[NSEntityDescription entityForName:@"System" inManagedObjectContext:self.managedObjectContext]];
    NSError * error = nil;
    NSArray * systems = [self.managedObjectContext executeFetchRequest:allSystems error:&error];

    //error handling goes here
    //for (NSManagedObject * system in systems) {


    NSManagedObject *system = systems[2];

    NSString *entityString = @"System";
    NSString * serverString = [NSString stringWithFormat:@"%@%@", kWebServiceAddress, entityString];
    NSURL *url = [NSURL URLWithString:serverString];
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:[self jsonSystemDictionary:(System *)system] options:kNilOptions error:&error];

    //NSLog([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); //debug only

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30.f];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: jsonData];

    self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

//}
}
4

1 回答 1

1

你将需要NSMutableURLRequest。使用它,您可以使用字符串setHTTPMethod并将其传递给它@"POST",然后根据需要使用您的属性NSManagedObject来填充URL,HTTPBody和/或HTTPHeader

于 2013-01-22T22:16:43.973 回答