【问题标题】:How to save the data in JSON dictionary and to send the web service post call?如何将数据保存在 JSON 字典中并发送 Web 服务后调用?
【发布时间】:2016-12-19 05:10:57
【问题描述】:

我有两个名为密码字段的文本字段,我将该文本保存在一个名为“Firststring”的字符串中。

我的疑问是如何将字符串值分配给我的 jsonDict 并进行 Web 服务发布调用?

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    你的方法是对的,你可以使用 Keys 直接将你的字符串添加到 Dict

    NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
    [jsonDict setObject:@"staticname" forKey:@"albert"];
    [jsonDict setObject:Firststring forKey:@"password"];
    

    update-1

    NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL HERE"]];
    [req setHTTPMethod:@"POST"];
     NSError *error = nil;
    
       NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
    [jsonDict setObject:@"staticname" forKey:@"albert"];
    [jsonDict setObject:Firststring forKey:@"password"];
    
     NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict 
    options:kNilOptions error:&error];
     NSString *postLength = [NSString stringWithFormat:@"%d",[data length]];
    [req addValue:postLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPBody:postData];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:req
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                // Do something 
               NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json);  
                                            }];
    
    [task resume];
    

    选择 2

    // 1
    NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    // 2
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]  initWithURL:url];
    request.HTTPMethod = @"POST";
    
     // 3
       NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
    [jsonDict setObject:@"staticname" forKey:@"albert"];
    [jsonDict setObject:Firststring forKey:@"password"];
    
     NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDict 
    options:kNilOptions error:&error];
    
    
    if (!error) {
     // 4
     NSURLSessionUploadTask *uploadTask = [session  uploadTaskWithRequest:request
    fromData:data completionHandler:^(NSData *data,NSURLResponse  *response,NSError *error) {
    // Handle response here
      // handle response
                 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json);
    }];
    
    // 5
    [uploadTask resume];
    

    注意 - 如果你想在 iOS 9 中访问服务器,你需要在你的 .PList 中添加 NSAllowsArbitraryLoads 例如参见 This

    【讨论】:

    • 所以之后我不知道如何将数据传递到我的数据库。例如我的 url 是:`http://some xample/api`我需要将这些 json 数据传递到我的服务器然后怎么做。我在问网络服务调用。怎么做
    • 好的,那么我将在哪里将参数传递给 url。你能添加你的两个代码并更新,以便我可以学习如何编码以及在哪里传递 jsonDict
    • 所以你的两个选择是以json格式将参数发送到api对吗??
    • 真的帮了大忙。我会处理json调用并回来..感谢您的宝贵时间
    【解决方案2】:

    像这样:

    NSDictionary *jsonDict = @{@"staticname":@"albert",
                               @"password":password};
    

    【讨论】:

      【解决方案3】:

      使用以下方法发布数据。

      -(IBAction)login:(id)sender{
              NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
              [dict setObject:self.txtUsername.text forKey:@"txt_user_email"];
              [dict setObject:self.txtPassword.text forKey:@"txt_user_pass"];
              [self postMethodWithDict:dict andURL:@"http:your API url here" ];
      
      }
      
      
      
      -(void) postMethodWithDict:(NSDictionary *)dict andURL:(NSString *)url{
      
          NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
          [request setHTTPMethod:@"POST"];
          [request setTimeoutInterval:30];
      
          NSString *boundary = [NSString stringWithFormat:@"14737809831466499882746641449"];
          NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
          [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
          NSMutableData *body = [NSMutableData data];
          [body appendData:[[NSString stringWithFormat:@"--%@\\r\\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
      
      NSLog(@"sending data  %@", dict);
      
          // additional method to call in between
          NSData *data = [self createFormData:dict withBoundary:boundary];
          [body appendData:[[NSString stringWithFormat:@"\\r\\n--%@\\r\\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
          [body  appendData:data];
          [request setHTTPBody:body];
      
          NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
          if(conn) {
              // connection success
              NSLog(@"connection success");
          }
          else {
              // deal with error
              NSLog(@"error occured");
          }
      }
      
      
      //  linked method
      - (NSData*)createFormData:(NSDictionary*)myDictionary withBoundary:(NSString*)myBounds {
          NSMutableData *myReturn = [[NSMutableData alloc] init];
          NSArray *formKeys = [myDictionary allKeys];
          for (int i = 0; i < [formKeys count]; i++) {
              [myReturn appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",myBounds] dataUsingEncoding:NSASCIIStringEncoding]];
              [myReturn appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@",[formKeys objectAtIndex:i],    [myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]];
          }
          return myReturn;
      }
      

      使用 NSURLConnection 委托方法来获取你的 api 的所有响应

      【讨论】:

        猜你喜欢
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-16
        • 2016-06-12
        相关资源
        最近更新 更多