【问题标题】:NSMutableRequest not working for the second time (ARC enabled)NSMutableRequest 第二次不工作(启用 ARC)
【发布时间】:2015-04-09 11:58:48
【问题描述】:

我通过单击 UIButton 执行 JSON POST 请求,提交后,可以完成 segue 执行。因此,提交值后,我无法再执行 POST 请求。它显示状态代码 200 并且响应正常。但是,数据不会反映在后端。这是我的代码:

(IBAction)transitsurveydone:(id)sender {
    if([tempArray count]!=0){
       /* alert= [[UIAlertView alloc] initWithTitle:@"Survey Submission"
                                          message:@"Please Enter your location"
                                         delegate:self
                                cancelButtonTitle:@"Modify"
                                otherButtonTitles:@"Submit",nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        alert.tag=2;
        [alert show];*/

        NSLog(@"Caption array is %@ %@",captionArray,tempArray);

        NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"myURL"]];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

        NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];


        NSMutableDictionary *d=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@10,@"\"Bus\"", nil];
            NSMutableArray *m=[[NSMutableArray alloc] init];

        NSString *str1,*str2,*str3,*str4;
               // Checking the format






        if(tempArray.count==1){
            for (int x=0; x<1; x++) {
                str1=[NSString stringWithFormat:@"\"%@\"",[captionArray objectAtIndex:x]];
                [d setObject:[tempArray objectAtIndex:x]  forKey:str1];


            }


        [request setHTTPBody:[[NSString stringWithFormat: @"{\n    \"instance\" : %@,\n    \"response_method\": \"web\",\n    \"routes\": [\n                {%@:%@}\n        ]\n}",randomString,str1,[d objectForKey:str1] ]dataUsingEncoding:NSUTF8StringEncoding]];
        }
          NSLog(@"%@:%@",str1,[d objectForKey:str1]);        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error) {

                                          if (error) {
                                              // Handle error...
                                              return;
                                          }

                                          if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                              NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                              NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                          }

                                          NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                          NSLog(@"Response Body:\n%@\n", body);
                                      }];
        [task resume];


        NSHTTPURLResponse *response = nil;
        NSError *error = nil;


        NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSLog(@"~~~~~ Status code: %d", [response statusCode]);

        if([response statusCode]==200){
            UIAlertView  *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Transit Survey submitted" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
            alert.transform = CGAffineTransformMakeTranslation( 10, 740);
            [alert show];
            [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1.0f];
            submitteddonthide=NO;
        }
        else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Transit Survey Submission Failed" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        alert.transform = CGAffineTransformMakeTranslation( 10, 740);
        [alert show];
        [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:1.0f];
        }


        if([prefs integerForKey:@"humandone"]==1){
            [self performSegueWithIdentifier:@"transittohuman" sender:nil];
        }
        else{
            [self performSegueWithIdentifier:@"gobackfromtransit" sender:nil];
        }


    }

`

以上代码在IBAction中

【问题讨论】:

  • 您可能想检查后端发生了什么。是否接收连接?如果它返回 200,它对数据做了什么?
  • 它包含字母数字格式的数据。但是,后端没有保存数据

标签: ios objective-c nsurlrequest nsurlsession nsmutableurlrequest


【解决方案1】:

您的代码看起来不错,没有任何问题。 如果此问题一直发生,请将“Advanced Rest Client”插件添加到 chrome 浏览器并测试您的服务器 URL 是否传递相应的输入值。如果此过程也无法在您的后端更新值,那么您的后端应该有一些问题。

【讨论】:

    【解决方案2】:

    一些想法:

    1. 您正在使用状态码来确定服务器是否正确插入了数据。您实际上应该让您的 Web 服务构建一个肯定的响应(在 JSON 中,会很棒),说明数据是否成功插入。您不应仅依赖 Web 服务器的请求响应代码。

    2. 我会用Charles 之类的东西观察请求,并确保它看起来正常。

    3. 您正在手动构建一个 JSON 请求,这非常脆弱。我建议使用 Charles 来观察请求,并将其复制并粘贴到 http://jsonlint.com 并确保它没问题。

    4. 更好的是,使用更强大且更易于使用的NSJSONSerialization

    5. 另外,您要发送此请求两次。丢失第二个请求(无论如何,您不应该执行同步请求)并将所有确认逻辑放入会话的完成处理程序块中。

    【讨论】:

      【解决方案3】:

      是的。经过一番挣扎后,清除 cookie 对我帮助很大:-

      这是一段代码,非常简单

       NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
       NSArray *cookies = [cookieStorage cookiesForURL:[NSURL URLWithString:urlString]];
          for (NSHTTPCookie *cookie in cookies) {
              NSLog(@"Deleting cookie for domain: %@", [cookie domain]);
              [cookieStorage deleteCookie:cookie];
          }
      

      感谢reddys先生和Rob的建议

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多