2013-04-24 2 views
-1

Я следовал учебник (http://www.raywenderlich.com/5492/working-with-json-in-ios-5), в котором я получил код для обработки веб-службы JSon (здесь мой веб-сервис: http://bit.ly/Y5430d)Web Service IOS не работает

Итак, я изменил свой URL, чтобы мой веб-сервис и objectforkey для представления моего (я не изменил ни одну из других переменных). Однако неформатированный json не проходит.

Что-то не так с моим веб-сервисом?

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1 
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://www.bushell.info/getResults.php"] //2 

#import "ViewController.h" 

@interface NSDictionary(JSONCategories) 
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress; 
-(NSData*)toJSON; 
@end 

@implementation NSDictionary(JSONCategories) 
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress 
{ 
    NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ]; 
    __autoreleasing NSError* error = nil; 
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
    if (error != nil) return nil; 
    return result; 
} 

-(NSData*)toJSON 
{ 
    NSError* error = nil; 
    id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error]; 
    if (error != nil) return nil; 
    return result;  
} 
@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    dispatch_async(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: kLatestKivaLoansURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
    }); 
} 

- (void)fetchedData:(NSData *)responseData { 
    //parse out the json data 
    NSError* error; 
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1 
                 options:kNilOptions 
                  error:&error]; 
    NSArray* latestLoans = [json objectForKey:@"Latest lotto"]; //2 

    NSLog(@"Latest lotto: %@", latestLoans); //3 

    // 1) Get the latest loan 
    NSDictionary* loan = [latestLoans objectAtIndex:0]; 

    // 2) Get the funded amount and loan amount 
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"]; 
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"]; 
    float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue]; 

    // 3) Set the label appropriately 
    humanReadble.text = [NSString stringWithFormat:@"Latest loan: %@ from %@ needs another $%.2f to pursue their entrepreneural dream", 
         [loan objectForKey:@"name"], 
         [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"], 
         outstandingAmount 
         ]; 

    //build an info object and convert to json 
    NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys: 
          [loan objectForKey:@"name"], @"who", 
          [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"], @"where", 
          [NSNumber numberWithFloat: outstandingAmount], @"what", 
          nil]; 

    //convert object to data 
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info 
                 options:NSJSONWritingPrettyPrinted 
                 error:&error]; 

    //print out the data contents 
    jsonSummary.text = [[NSString alloc] initWithData:jsonData 
              encoding:NSUTF8StringEncoding]; 

} 

@end 
+1

Вы объявляете эту ошибку 'NSError * ;, но вы никогда не проверяете эту ошибку. – sosborn

ответ

0

Что-то не так с моей веб-сервиса?

Простой способ рассказать - получить к нему доступ с чем-то отличным от вашего приложения. Программа командной строки curl - отличный инструмент для проверки результатов вызова веб-службы. Даже Safari может помочь здесь, особенно если вы включили веб-инспектора (меню «Настройки» -> «Дополнительно» - «Показать конструкцию» в строке меню). На самом деле все, что позволяет увидеть результаты запроса, должно работать.

Еще один способ проверить вашу службу - использовать веб-прокси-инструмент, такой как Charles. Вы можете настроить устройство на использование Карла в качестве прокси-сервера HTTP, а затем Чарльз сможет показать вам весь трафик между вашим приложением и сервером.

+1

Спасибо, это очень помогло! – Bushell

Смежные вопросы