iOS - 如何将 JSON 对象附加到 Web 请求? (不使用 NSURLConnection)

标签 ios json web-services nsdata nsurlrequest

我正在尝试向我在网络服务器上设置的后端 API 发送一些网络请求。 但是,为了使事情变得通用,我想将整个 JSON 对象发送到后端,并在那里进行所有数据过滤以确定请求的用途、要传递的参数等。

我将从一个类向不同的服务发出许多请求,因此我不想使用 NSURLConnection,因为它会变得困惑,必须过滤完成处理程序中的所有结果以确定最初提取的是哪个请求。

我喜欢 NSURLConnection 允许您附加这样的 JSON 对象,但我想知道如何使用不同的方法来实现它(例如 [NSData dataWithContentsOfURL:])

NSMutableDictionary *postObject = [[NSMutableDictionary alloc] init];
[postObject setValue:@"login" forKey:@"request"];
[postObject setValue:inputUsername.text forKey:@"userName"];
[postObject setValue:inputPassword.text forKey:@"password"];

NSData *postData = [NSJSONSerialization dataWithJSONObject:postObject options:0 error:NULL];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"WEB_URL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:20];

有什么建议吗?

最佳答案

我这样做的方法是创建一个带有 NSURLConnection 的 NSObject 类,并在该类上设置一个属性标记。然后,当下载完成时,您的 NSObject/NSURLConnection 类的连接将自身返回给委托(delegate)。您有一个类似于下面的 -(void)downloadFinished 示例的方法来处理委托(delegate)中的回复。

在 NSObject 类中,您使用 NSJsonSerialization 将 NSDictionary 转换为 Json 并将其附加到 NSURLConnection。

我希望可以将您链接到 Github 上的 JsonHelper 类,但我还没有将其上传到 Github :(。

示例请求:

NSDictionary *post = [NSDictionary dictionaryWithObjectsAndKeys:@"Json_Value",@"Json_Key",nil];

JsonHelper *jsonHelper = [[JsonHelper alloc]initWithURL:@"http://mycoolwebservice.com" withDictionary:post
withMethod:@"POST" showIndicator:NO withDelegate:self withCache:NO];
[jsonHelper setTag:1];
[jsonHelper connectionStart];

委托(delegate)回复示例:

-(void)downloadFinished:(id)sender
{
   if ([sender isKindOfClass:[JsonHelper class]]) {

    NSError *error = nil;
    JsonHelper *jsonHelper = (JsonHelper*)sender;
        NSData *data = [[NSData alloc]initWithData:jsonHelper.receivedData];
        NSString *returnString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];    

    if (jsonHelper.tag == 0) {

    // Do Something
    }

    else if (jsonHelper.tag == 1) {

    // Do Something Else
    }
  }    
}

使用此示例编写自己的自定义类来执行或多或少相同的操作应该不会太困难。

关于iOS - 如何将 JSON 对象附加到 Web 请求? (不使用 NSURLConnection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558568/

相关文章:

ios - 在 UITableViewCell iOS 中播放视频

ios - 选项卡栏项目 - 选定/未选定图标

Javascript + AngularJS - 比较 JSON

java - 带有 Java 的 Wss4jSecurityInterceptor 的 SOAP WS-Addressing 属性

wcf - 帮助 .NET 开发人员使用 Coldfusion 使用 WCF 服务

ios - 如何获取动画 UIImageView 的坐标

ios - Picker View 后面的 UIKeyboard

.net - WCF - 客户端代理配置与服务 web.config 不匹配

javascript - 根据id将json数组转换为单个数组

php - 统一数组进行 JSON 编码?