2014-06-15 91 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