我有一个Web服务,允许我更新数据库中的记录。 表中的列如下:
我正在使用以下内容从Web服务获取数据。
NSString *urlString = [NSString stringWithFormat:@"%@", inventoryAndActionsWebservice];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
然后像这样推进字典:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSLog(@"WE HAS THE DATAS");
NSDictionary *inventory = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
// Then storing the values in CoreData here
}
}
更新网络服务的语法是什么?它期望服务调用(POST)主体中的对象。
答案 0 :(得分:1)
NSMutableURLRequest
让你setHTTPBody:
和setHTTPMethod:.
@" POST" is the way to do a post. Most services need to know the body length and encoding set in headers. (see
addValue:forHTTPHeaderField:`)。
这个主题很棘手的唯一原因是因为开发人员被迫同时解决两个问题:什么构成对我的服务器的有效请求,以及(2)我如何用iOS形成该请求?一旦得到有效请求,第(2)部分实际上非常简单。
最好的方法是使用curl(或类似的东西)来运行一个例子。然后继续在iOS中生成该请求。如果您遇到问题,请在此处提出以下问题:&#34;我知道我的服务器需要X,这是我生成X的代码,但我收到此错误Y&#34;。< / p>
答案 1 :(得分:0)
所以我一直在寻找的语法最终是:
NSString *jSONString = [NSString stringWithFormat:@"{\"MediaInventoryObjectsId\":%d,\"AssetId\":%d,\"Quantity\":%d,\"SerialNumber\":\"%@\",\"Description\":\"%@\",\"AllowActions\":%d,\"Retired\":%d}",inventoryObjectId, assetID, quantity, serialNumber, description, allowActions, retired];
// Convert jSON string to data
NSData *putData = [jSONString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Instantiate a url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// Set the request url format
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%d", inventoryAndActionsWebservice, inventoryObjectId]]];
[request setHTTPMethod:@"PUT"];
[request setHTTPBody:putData];
[request setValue:@"application/json" forHTTPHeaderField:@"content-type"];
// Send data to the webservice
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];