0
  1. 我有一张二维码图片。我在 iOS 中扫描该图像并获得一个网址。
  2. 我通过 JSON 对象将该 URL 发布到 Web 服务,并获得一个“ProjectID”作为回报。
  3. 如果该 projectID 具有正值,我应该返回 YES,表示扫描的 URL 对 web 服务有效,否则返回 NO。

[出于测试目的,我对应该返回 YES 的 URL 进行了硬编码。我稍后会得到扫描的 URL]

如何提取我在日志中获取的 projectID 并检查条件。

这是我编码的

NSError *error;

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

 NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"test@yahoo.com" ,@"EmailID", @"http://www.yahoo.com", @"URL", @"", @"Phone", @"", @"UserID", nil];


   NSURL *url = [NSURL URLWithString:@"http:// some url"];

   NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

NSData *requestData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];

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

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        [connection start];
       [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
       if(error || !data)
       {
           NSLog(@"JSON NOT posted");
       }
        else
        {
            id jsonObject = [NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingAllowFragments error:Nil];

            if([jsonObject respondsToSelector:@selector(objectForKey:)])
            {
                NSDictionary *dictionaryForUserID = [jsonObject valueForKey:@"ProjID"];
                NSLog(@" Project Id = %@", dictionaryForUserID); 

    /* I get "Project ID = (null)"  here whereas I get one positive value in the log. My question is how to get the projectID in log? */

    /* log output ::

    2013-08-20 11:57:34.765 appname[585:5903]  Project Id = (null)

    2013-08-20 11:57:34.766 appname[585:5903] JSON data posted!

    2013-08-20 11:57:34.769 appname[585:c07] Data: 
    {"ProjID":"5","ProjName":null,"URL":null,"EmailID":null,"Phone":null,"userId":null}{"ProjID":"5","ProjName":null,"URL":null,"EmailID":null,"Phone":null,"userId":null}

    */

            }
            NSLog(@"JSON data posted!");
        }
    }];
4

2 回答 2

2

好吧,问题在于您正在解析请求数据而不是响应数据。

试试这个:

id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:Nil];
于 2013-08-20T07:06:43.717 回答
1

仔细查看您的代码。您正在解析requestData,而不是data从服务器接收到的。祝你好运!

于 2013-08-20T07:05:56.760 回答