Разработчик приложения для iOS - NSMutableURLRequest - ноль

Я новичок в разработке iOS. Теперь я столкнулся со странной проблемой. Когда я запускал следующие коды на симуляторе iPhone 5, все работало нормально. Тем не менее, это не работает на моем реальном iPhone 5. Кто-нибудь может сделать мне одолжение, чтобы помочь мне выяснить причину? OBJ-C: ошибка NSError *;

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@1 forKey:@"driverId"];
[dictionary setValue:@1 forKey:@"busId"];
[dictionary setValue:@1 forKey:@"lineId"];

NSData *postData = nil;
NSString *requestData = @"";
NSString *urlPath = @"myurl";
if([NSJSONSerialization isValidJSONObject:dictionary]){
    postData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString *str = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
    requestData = [requestData stringByAppendingString:str];

    postData = [NSData dataWithBytes:[requestData UTF8String] length:[requestData length]];
}

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSURL *url = [NSURL URLWithString:urlPath];

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSString *status = [responseDic objectForKey:@"status"];

Сопоставив "запрос" с "ноль", я обнаружил, что запрос был ноль.

Ошибка была:

2014-07-23 19: 13: 54.698 ShuttleBusForDriver [2958: 60b] nil request 2014-07-23 19: 13: 54.699 ShuttleBusForDriver [2958: 60b] responseDate: (null) 2014-07-23 19: 13: 54.701 ShuttleBusForDriver [2958: 60b] * Нагрузочный приложение из - за неперехваченного исключением 'NSInvalidArgumentException', причина: 'параметр данных равен нулю' * Первый стек бросить вызов: (0x2fc96ecb 0x3a431ce7 0x2fc96e0d 0x30624967 0xdfa55 0xde785 0x324cca33 0x324cc7f1 0x32658bf3 0x3257646f 0x32576279 0x32576211 0x324c82e5 0x3214431b 0x3213fb3f 0x3213f9d1 0x3213f3e5 0x3213f1f7 0x324cb99f 0x2fc61faf 0x2fc61477 0x2fc5fc67 0x2fbca729 0x2fbca50b 0x34b396d3 0x3252b871 0xdc69c 0xdc6d8 0x3a92fab7) libC++abi.dylib: завершение с исключением типа исключение

3 ответа

Решение

@JingDu Ваш сбой происходит, потому что вы пытаетесь декодировать нулевой объект в NSDictionary в этом фрагменте кода:

NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSString *status = [responseDic objectForKey:@"status"];

Иногда ваш urlconnection будет тайм-аут или сервер возвращает ошибку, что делает responseData равным нулю. Таким образом, вы должны проверить, существует ли responseData или нет. Сделай это так:

if (responseData)
{
    NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
    NSString *status = [responseDic objectForKey:@"status"];
}

Кстати, вы должны опубликовать свой символический отчет о сбое, чтобы помочь другим быстро найти ваши проблемы.

Пожалуйста, отметьте этот ответ как принятый, если он устраняет сбой. Спасибо.

@JingDu Приносим свои извинения за то, что я не могу добавить комментарий из-за проблемы с сайтом stackru. Символический отчет о сбое - это символический отчет, который выглядит следующим образом:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(
 0   CoreFoundation                      0x0284d1e4 __exceptionPreprocess + 180
 1   libobjc.A.dylib                     0x01c7e8e5 objc_exception_throw + 44
 2   CoreFoundation                      0x0284cfbb +[NSException raise:format:] + 139
 3   Foundation                          0x017b7bd2 +[NSJSONSerialization JSONObjectWithData:options:error:] + 67
 4   Test                                0x00003eb8 -[ViewController viewDidLoad] + 136
 5   UIKit                               0x0085033d -[UIViewController loadViewIfRequired] + 696
 6   UIKit                               0x008505d9 -[UIViewController view] + 35
 7   UIKit                               0x00770267 -[UIWindow addRootViewControllerViewIfPossible] + 66
 8   UIKit                               0x007705ef -[UIWindow _setHidden:forced:] + 312
 9   UIKit                               0x0077086b -[UIWindow _orderFrontWithoutMakingKey] + 49
 10  UIKit                               0x0077b3c8 -[UIWindow makeKeyAndVisible] + 65
 11  UIKit                               0x0072bbc0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 2097
 12  UIKit                               0x00730667 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
 13  UIKit                               0x00744f92 -[UIApplication handleEvent:withNewEvent:] + 3517
 14  UIKit                               0x00745555 -[UIApplication sendEvent:] + 85
 15  UIKit                               0x00732250 _UIApplicationHandleEvent + 683
 16  GraphicsServices                    0x0255cf02 _PurpleEventCallback + 776
 17  GraphicsServices                    0x0255ca0d PurpleEventCallback + 46
 18  CoreFoundation                      0x027c8ca5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
 19  CoreFoundation                      0x027c89db __CFRunLoopDoSource1 + 523
 20  CoreFoundation                      0x027f368c __CFRunLoopRun + 2156
 21  CoreFoundation                      0x027f29d3 CFRunLoopRunSpecific + 467
 22  CoreFoundation                      0x027f27eb CFRunLoopRunInMode + 123
 23  UIKit                               0x0072fd9c -[UIApplication _run] + 840
 24  UIKit                               0x00731f9b UIApplicationMain + 1225
 25  Test                                0x000026bd main + 141
 26  libdyld.dylib                       0x02d30725 start + 0
 )
libc++abi.dylib: terminating with uncaught exception of type NSException

Это из похожего кода, как у вас:

 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil' * First throw call stack: (0x2fc96ecb 0x3a431ce7 0x2fc96e0d 0x30624967 0xdfa55 0xde785 0x324cca33 0x324cc7f1 0x32658bf3 0x3257646f 0x32576279 0x32576211 0x324c82e5 0x3214431b 0x3213fb3f 0x3213f9d1 0x3213f3e5 0x3213f1f7 0x324cb99f 0x2fc61faf 0x2fc61477 0x2fc5fc67 0x2fbca729 0x2fbca50b 0x34b396d3 0x3252b871 0xdc69c 0xdc6d8 0x3a92fab7) libc++abi.dylib: terminating with uncaught exception of type NSException

Это проблема:

NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

Это решение:

if ([responseData length] > 0){
    NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

Проверьте длину данных, прежде чем передавать их в NSJSONSerialization. Проходя это ноль нет нет нет.

Другие вопросы по тегам