2014-06-15 21 views
-1

我的API的答案:{ “回应”: “成功”}IOS JSON授权

所以,如果 “成功” - 用户将被记录

代码:

NSString *stringURL = @"........"; 
    NSURL *url = [[NSURL alloc] initWithString:stringURL]; 
    NSData *urlData = [NSData dataWithContentsOfURL:url]; 

    NSError *error; 
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error]; 

    if ([[json objectForKey:@"response"] isEqual:@"success"]) 
     return true; 
    else 
     return false; 

什么时我做错了?

+0

很难用基本没有信息说。你不会说你收到的是什么JSON数据,你不会说什么JSON或错误包含。你听说过NSLog吗? – gnasher729

+0

我只有两个JSON答案:{“response”:“success”}或{“response”:“not success”}。 – vasilybodnarchuk

+0

如果“成功”,我想成为true,如果“不成功”,则成功false – vasilybodnarchuk

回答

0

的NSLog和检查什么是响应

还可以使用 “isEqualToString” insted的的 “的isEqual

NSURL *myURL = [NSURL URLWithString:@"Your URL"]; 
NSLog(@"myURL =%@", myURL); 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; 
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] 
         completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
{ 
    // check the list of status codes here :http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success 

    if ([(NSHTTPURLResponse *)response statusCode]==200) 
    { 
     NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     NSLog(@"Response from Server in string =%@", jsonString); 
     id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; 
     NSLog(@"Response from Server in JSON object =%@", jsonObject); 
     if ([[jsonObject objectForKey:@"response"] isEqualToString:@"success"]) 
      // Write code for True 
     else 
      // Write code for False 
    } 
    else 
    { 
     // Some Error 
    } 
}]; 
+0

不仅200是成功状态码。 – arturdev

+0

@arturdev耶我知道这一点。实际上从2开始的代码用于成功。 http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success –

+0

谢谢!但我不能编译它。错误行[NSURLConnection sendAsynchronousRequest:请求队列:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *响应,NSData *数据,NSError *错误) – vasilybodnarchuk