UNIRest: switch to a new ViewController on an Asynchronous HTTP response - ios

I'm using the UNIRest library and I'm trying to switch to another ViewController on the response of an HTTP GET method.
[[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:GEtFamilyMembers];
}] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
NSLog(#"res: %#", response.body);
if (response.code == 200) {
GCHFamilyMembersViewConroller* fmViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"gchFamilyMembers"];
self.navigationController.viewControllers = #[fmViewController];
[self.mm_drawerController setCenterViewController:self.navigationController withCloseAnimation:YES completion:nil];
} else {
[self showToast:#"Something went wrong, Please try again after some time."];
}
}];
Even after printing the response using NSLog. Nothing happens for about 30 seconds. Then suddenly app crashes.
I thought it's because Asynch call blocks UI so I tired a method like:
- (void) gotoSelectFamilyMembers {
dispatch_async(dispatch_get_main_queue(), ^{
GCHFamilyMembersViewConroller* fmViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"gchFamilyMembers"];
self.navigationController.viewControllers = #[fmViewController];
[self.mm_drawerController setCenterViewController:self.navigationController withCloseAnimation:YES completion:nil];
});
}
but still the app crashes.
Earlier when I was using a Synchronous call it was working. But not now.
Please help!
EDIT:
2016-05-02 17:58:22.695 Checkme Mobile[6208:136321] *** Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /SourceCache/UIKit_Sim/UIKit-3347.44.2/Keyboard/UIKeyboardTaskQueue.m:374
2016-05-02 17:58:22.728 Checkme Mobile[6208:136224] NSScanner: nil string argument
2016-05-02 17:58:22.728 Checkme Mobile[6208:136224] NSScanner: nil string argument
2016-05-02 17:58:23.730 Checkme Mobile[6208:136224] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'
*** First throw call stack:
(
0 CoreFoundation 0x00000001094a6c65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000108da2bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001094a6aca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00000001089b798f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 UIKit 0x0000000107d887d6 -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] + 151
5 UIKit 0x0000000107829912 -[UIKeyboardImpl setDelegate:force:] + 473
6 UIKit 0x0000000107ad44ad -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:] + 1002
7 UIKit 0x0000000107adc834 -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:reset:] + 504
8 UIKit 0x000000010778e181 -[UINavigationController navigationTransitionView:didStartTransition:] + 578
9 UIKit 0x00000001079948bc -[UINavigationTransitionView transition:fromView:toView:] + 655
10 UIKit 0x0000000107792170 -[UINavigationController _startTransition:fromViewController:toViewController:] + 2984
11 UIKit 0x0000000107792408 -[UINavigationController _startDeferredTransitionIfNeeded:] + 523
12 UIKit 0x0000000107792ece -[UINavigationController __viewWillLayoutSubviews] + 43
13 UIKit 0x00000001078dd6d5 -[UILayoutContainerView layoutSubviews] + 202
14 UIKit 0x00000001076b09eb -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
15 QuartzCore 0x0000000109d83ed2 -[CALayer layoutSublayers] + 146
16 QuartzCore 0x0000000109d786e6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
17 QuartzCore 0x0000000109d78556 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
18 QuartzCore 0x0000000109ce486e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
19 QuartzCore 0x0000000109ce5a22 _ZN2CA11Transaction6commitEv + 462
20 QuartzCore 0x0000000109ce5c99 _ZN2CA11Transaction14release_threadEPv + 199
21 libsystem_pthread.dylib 0x000000010a35172a _pthread_tsd_cleanup + 86
22 libsystem_pthread.dylib 0x000000010a351451 _pthread_exit + 117
23 libsystem_pthread.dylib 0x000000010a3506cd _pthread_wqthread + 879
24 libsystem_pthread.dylib 0x000000010a34e40d start_wqthread + 13
)
2016-05-02 17:58:23.730 Checkme Mobile[6208:136321] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'
*** First throw call stack:
(
0 CoreFoundation 0x00000001094a6c65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000108da2bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001094a6aca +[NSException raise:format:arguments:] + 106
3 Foundation 0x00000001089b798f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
4 UIKit 0x0000000107d887d6 -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] + 151
5 UIKit 0x0000000107829912 -[UIKeyboardImpl setDelegate:force:] + 473
6 UIKit 0x0000000107ad44ad -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:] + 1002
libc++abi.dylib: 7 UIKit 0x0000000107adc834 -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:reset:] + 504
8 UIKit 0x000000010778e181 -[UINavigationController navigationTransitionView:didStartTransition:] + 578
9 UIKit 0x00000001079948bc -[UINavigationTransitionView transition:fromView:toView:] + 655
10 UIKit 0x0000000107792170 -[UINavigationController _startTransition:fromViewController:toViewController:] + 2984
11 UIKit 0x0000000107792408 -[UINavigationController _startDeferredTransitionIfNeeded:] + 523
12 UIKit 0x0000000107792ece -[UINavigationController __viewWillLayoutSubviews] + 43
13 UIKit 0x00000001078dd6d5 -[UILayoutContainerView layoutSubviews] + 202
14 UIKit 0x00000001076b09eb -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
15 QuartzCore 0x0000000109d83ed2 -[CALayer layoutSublayers] + 146
16 QuartzCore 0x0000000109d786e6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
17 QuartzCore 0x0000000109d78556 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
18 QuartzCore 0x0000000109ce486e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
19 QuartzCore 0x0000000109ce5a22 _ZN2CA11Transaction6commitEv + 462
20 QuartzCore 0x0000000109ce5c99 _ZN2CA11Transaction14release_threadEPv + 199
21 libsystem_pthread.dylib 0x000000010a35172a _pthread_tsd_cleanup + 86
22 libsystem_pthread.dylib 0x000000010a351451 _pthread_exit + 117
23 libsystem_pthread.dylib 0x000000010a3506cd _pthread_wqthread + 879
24 libsystem_pthread.dylib 0x000000010a34e40d start_wqthread + 13
)
terminating with uncaught exception of type NSExceptionlibc++abi.dylib:
terminating with uncaught exception of type NSException
(lldb)
EDit:
- (IBAction)loginAction:(id)sender {
self.email = usernameTextField.text;
self.password = passwordTextField.text;
if(!([self.email isEqualToString:#""] && [self.password isEqualToString:#""])) {
[self performLogin];
} else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"error" message:#"Enter both username and password." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
- (void) performLogin {
NSDictionary* headers = #{#"Content-Type": #"application/x-www-form-urlencoded"};
NSDictionary* parameters = #{#"username": self.email, #"password": self.password};
[[NSThread currentThread] isMainThread] ? NSLog(#"1MAIN THREAD") : NSLog(#"1NOT MAIN THREAD");
self.loginConnection = [[UNIRest post:^(UNISimpleRequest *request) {
[request setUrl:LOgin];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
// This is the asyncronous callback block
[[NSThread currentThread] isMainThread] ? NSLog(#"2MAIN THREAD") : NSLog(#"2NOT MAIN THREAD");
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSString *string = [[NSString alloc] initWithData:rawBody encoding:NSUTF8StringEncoding];
NSLog(#"response signup: %#", string);
if (response.code == 200) {
[self processLoginResponse:body];
}
}];
}
- (void) processLoginResponse:(UNIJsonNode *) body {
if ([body.JSONObject[#"status"] boolValue] == YES) {
NSString *firstName = body.JSONObject[#"firstName"];
NSString *lastName = body.JSONObject[#"lastName"];
NSString *name = [firstName stringByAppendingString:lastName];
NSMutableDictionary *mDictionary = [[NSMutableDictionary alloc] init];
[mDictionary setObject:body.JSONObject[#"accountId"] forKey:#"accountId"];
[mDictionary setObject:name forKey:#"name"];
[mDictionary setObject:#"Custodian" forKey:#"relation"];
[self fetchFamilyMembers:mDictionary];
} else {
[self showAlert:body.JSONObject[#"message"]];
}
}
- (void) fetchFamilyMembers:(NSMutableDictionary *) mDictionary {
[[NSThread currentThread] isMainThread] ? NSLog(#"3MAIN THREAD") : NSLog(#"3NOT MAIN THREAD");
self.fmConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:GEtFamilyMembers];
}] asJsonAsync:^(UNIHTTPJsonResponse* response, NSError *error) {
NSLog(#"res: %#", response.body);
if (response.code == 200) {
[[NSThread currentThread] isMainThread] ? NSLog(#"4MAIN THREAD") : NSLog(#"4NOT MAIN THREAD");
NSData *rawBody = response.rawBody;
NSString *string = [[NSString alloc] initWithData:rawBody encoding:NSUTF8StringEncoding];
NSLog(#"family signup: %#", string);
[[NSThread currentThread] isMainThread] ? NSLog(#"5MAIN THREAD") : NSLog(#"5NOT MAIN THREAD");
[self processFamilyMembersResponse:mDictionary :response.body];
} else {
[self showToast:#"Something went wrong, Please try again after some time."];
}
}];
}
- (void) processFamilyMembersResponse:(NSMutableDictionary *) mDictionary :(UNIJsonNode *) body {
NSArray *fmArray = body.JSONArray;
if (fmArray == nil || [fmArray count] == 0) {
NSNumber *accountId = (NSNumber *)[mDictionary objectForKey:#"accountId"];
} else {
NSMutableArray *mArray = [[NSMutableArray alloc] init];
[mArray addObject:mDictionary];
for (int i = 0; i < fmArray.count; i++) {
NSDictionary *fmDictionary = [fmArray objectAtIndex:i];
mDictionary = [[NSMutableDictionary alloc] init];
NSNumber *accountId = (NSNumber *)[fmDictionary objectForKey:#"id"];
[mDictionary setObject:accountId forKey:#"accountId"];
[mDictionary setObject:[fmDictionary objectForKey:#"name"] forKey:#"name"];
[mDictionary setObject:[fmDictionary objectForKey:#"relation"] forKey:#"relation"];
[mArray addObject:mDictionary];
}
[[NSThread currentThread] isMainThread] ? NSLog(#"6MAIN THREAD") : NSLog(#"6NOT MAIN THREAD");
[self gotoSelectFamilyMembers:mArray];
}
}
- (void) gotoSelectFamilyMembers:(NSMutableArray *) mArray {
dispatch_async(dispatch_get_main_queue(), ^{
GCHFamilyMembersViewConroller* fmViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"gchFamilyMembers"];
fmViewController._tblData = mArray;
self.navigationController.viewControllers = #[fmViewController];
[self.mm_drawerController setCenterViewController:self.navigationController withCloseAnimation:YES completion:nil];
});
}

Try below code:
dispatch_async(dispatch_get_main_queue(), ^{
GCHFamilyMembersViewConroller* fmViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"gchFamilyMembers"];
fmViewController._tblData = mArray;
((AppDelegate*)[[UIApplication sharedApplication]delegate]).navigationController.viewControllers = #[fmViewController];
[self.mm_drawerController setCenterViewController:((AppDelegate*)[[UIApplication sharedApplication]delegate]).navigationController withCloseAnimation:YES completion:nil];
});

You're using the asynchronous calls of Unirest and the response should be called on the UI thread (Main thread). Usually libraries similar to this deliver the result on the main thread. Therefore, I think you do not need to specifically call dispatch_async on the main queue. However, you can use the following check to see whether it gets called on the main thread or not.
[[NSThread currentThread] isMainThread] ? NSLog(#"MAIN THREAD") : NSLog(#"NOT MAIN THREAD");
Here's what I suspect
Your ViewController creation method has some fault and is consuming time
Your response is very large
I suggest that you call the following without any web service calls to confirm that they do not cause the crash.
GCHFamilyMembersViewConroller* fmViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"gchFamilyMembers"];
self.navigationController.viewControllers = #[fmViewController];
[self.mm_drawerController setCenterViewController:self.navigationController withCloseAnimation:YES completion:nil];

Related

Populate TableView with names of files in documents directory - exception with empty array

I am trying to populate a table view with the file names of the files located in the documents directory but when the button is clicked to show the table view the app crashes saying that the object at index is 0. but there are 14 objects in the array. What could be the fault?
#implementation loadDataTVC
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void) viewWillAppear:(BOOL)animated{
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
NSLog(#"%lu", (unsigned long)[sharedManager.directoryContent count]);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
if (sharedManager.directoryContent.count > 0) {
return (unsigned long)[sharedManager.directoryContent count];
}
else{
return 1;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"files" forIndexPath:indexPath];
DataSource *sharedManager = [DataSource sharedManager];
NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
sharedManager.directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
if (sharedManager.directoryContent.count > 0) {
cell.textLabel.text = [NSString stringWithFormat:#"%#", [sharedManager.directoryContent objectAtIndex:indexPath.row]];
}
else{
cell.textLabel.text = #"No data Available";
}
return cell;
}
The log:
2016-05-18 15:00:44.502 GeoData Grapher[4554:331076] 14
2016-05-18 15:00:47.412 GeoData Grapher[4554:331076] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'
*** First throw call stack:
(
0 CoreFoundation 0x000000010d2cdd85 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010cd41deb objc_exception_throw + 48
2 CoreFoundation 0x000000010d275885 -[__NSArray0 objectAtIndex:] + 101
3 GeoData Grapher 0x000000010a5f07d6 -[DeviceListTVC prepareForSegue:sender:] + 326
4 UIKit 0x000000010bcc95d5 -[UIStoryboardSegueTemplate _performWithDestinationViewController:sender:] + 369
5 UIKit 0x000000010bcc9433 -[UIStoryboardSegueTemplate _perform:] + 82
6 UIKit 0x000000010bcc96f7 -[UIStoryboardSegueTemplate perform:] + 156
7 UIKit 0x000000010b583a8d -[UIApplication sendAction:to:from:forEvent:] + 92
8 UIKit 0x000000010b991067 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 152
9 UIKit 0x000000010b583a8d -[UIApplication sendAction:to:from:forEvent:] + 92
10 UIKit 0x000000010b6f6e67 -[UIControl sendAction:to:forEvent:] + 67
11 UIKit 0x000000010b6f7143 -[UIControl _sendActionsForEvents:withEvent:] + 327
12 UIKit 0x000000010b6f72be -[UIControl _sendActionsForEvents:withEvent:] + 706
13 UIKit 0x000000010b6f6263 -[UIControl touchesEnded:withEvent:] + 601
14 UIKit 0x000000010b5f699f -[UIWindow _sendTouchesForEvent:] + 835
15 UIKit 0x000000010b5f76d4 -[UIWindow sendEvent:] + 865
16 UIKit 0x000000010b5a2dc6 -[UIApplication sendEvent:] + 263
17 UIKit 0x000000010b57c553 _UIApplicationHandleEventQueue + 6660
18 CoreFoundation 0x000000010d1f3301 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
19 CoreFoundation 0x000000010d1e922c __CFRunLoopDoSources0 + 556
20 CoreFoundation 0x000000010d1e86e3 __CFRunLoopRun + 867
21 CoreFoundation 0x000000010d1e80f8 CFRunLoopRunSpecific + 488
22 GraphicsServices 0x000000010eb7aad2 GSEventRunModal + 161
23 UIKit 0x000000010b581f09 UIApplicationMain + 171
24 GeoData Grapher 0x000000010a5f405f main + 111
25 libdyld.dylib 0x000000011253c92d start + 1
26 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
The Segue:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *selectedPath = [self.tableView indexPathForCell:sender];
AirconsoleDevice *selectedDevice = self.manager.defaultDevice;
if (selectedPath.section == 0) {
selectedDevice = self.currentDevices[selectedPath.row];
}
if ([segue.identifier isEqualToString:#"session_details"]) {
AirconsoleSession *session = [[AirconsoleSession alloc] initWithDevice:selectedDevice];
currentSession = session;
SessionDetailsVC *sdvc = segue.destinationViewController;
sdvc.session = session;
} else {
// we are presenting the Device Details
DeviceDetailsTVC *ddvc = [segue.destinationViewController viewControllers][0];
ddvc.device = selectedDevice;
}
}
The problem is in this line
DeviceDetailsTVC *ddvc = [segue.destinationViewController viewControllers][0];
ddvc.device = selectedDevice;
The destination controller is I assume a Navigation controller. And you are accessing the first controller in the stack.
Check this is actually set up correctly in the Storyboard. Because thats what the line of code expects, but the crash says it cannot find any member in the viewControllers array.
AFAIK it has nothing to do with the table view and 14 items.

Issue Paging Twitter with AFNetworking

I am attempting to page tweets on a existing Tweet NSMutableArray with AFNetworking. However I recieve this error every time my app is run:
-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object
2015-01-18 00:17:29.869 Floadt[91615:3385865] STACK TRACE :
(
0 CoreFoundation 0x00000001055a1f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010523abb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001055a1e6d +[NSException raise:format:] + 205
3 CoreFoundation 0x000000010559a6ea -[__NSCFArray insertObject:atIndex:] + 106
4 CoreFoundation 0x00000001054c6a43 -[NSMutableArray insertObjects:count:atIndex:] + 179
5 CoreFoundation 0x00000001054c6774 -[NSMutableArray insertObjectsFromArray:range:atIndex:] + 372
6 CoreFoundation 0x00000001054c6574 -[NSMutableArray addObjectsFromArray:] + 612
7 Floadt 0x0000000101e91f85 __57-[TwitterTableViewController fetchNextTwitterPageWithID:]_block_invoke_2 + 117
8 CoreFoundation 0x00000001055029c4 __NSArrayEnumerate + 596
9 Floadt 0x0000000101e91e56 __57-[TwitterTableViewController fetchNextTwitterPageWithID:]_block_invoke + 230
10 Floadt 0x0000000101e73223 __64-[AFJSONRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke91 + 51
11 libdispatch.dylib 0x00000001076fbba6 _dispatch_call_block_and_release + 12
12 libdispatch.dylib 0x00000001077197f4 _dispatch_client_callout + 8
13 libdispatch.dylib 0x00000001077028fb _dispatch_main_queue_callback_4CF + 949
14 CoreFoundation 0x0000000105509fe9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
15 CoreFoundation 0x00000001054cceeb __CFRunLoopRun + 2043
16 CoreFoundation 0x00000001054cc486 CFRunLoopRunSpecific + 470
17 GraphicsServices 0x0000000106f299f0 GSEventRunModal + 161
18 UIKit 0x0000000103f82420 UIApplicationMain + 1282
19 Floadt 0x0000000101ee5f73 main + 115
20 libdyld.dylib 0x000000010774e145 start + 1
21 ??? 0x0000000000000001 0x0 + 1
Paging Method
-(void)fetchNextTwitterPageWithID:(NSString *)objectID {
self.twitterClient = [[AFOAuth1Client alloc] initWithBaseURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/"] key:#"XXXXXXXXXXX" secret:#"XXXXXXXXXXXX"];
NSDictionary *parameters = #{
#"max_id" :objectID
};
AFOAuth1Token *twitterToken = [AFOAuth1Token retrieveCredentialWithIdentifier:#"TwitterToken"];
[self.twitterClient setAccessToken:twitterToken];
[self.twitterClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self.twitterClient getPath:#"statuses/home_timeline.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableArray *responseArray = (NSMutableArray *)responseObject;
[responseArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[tweets addObjectsFromArray:responseObject];
[self.tableView reloadData];
}];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Detecting the Bottom of the Page
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
NSDictionary *totalArray = tweets[indexPath.row];
NSString *cellID = [totalArray objectForKey:#"id"];
[self fetchNextTwitterPageWithID:cellID];
}
}
According to what I understand from you code, here is my answer for a correction:
-(void)fetchNextTwitterPageWithID:(NSString *)objectID {
self.twitterClient = [[AFOAuth1Client alloc] initWithBaseURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/"] key:#"XXXXXXXXXXX" secret:#"XXXXXXXXXXXX"];
NSDictionary *parameters = #{
#"max_id" :objectID
};
AFOAuth1Token *twitterToken = [AFOAuth1Token retrieveCredentialWithIdentifier:#"TwitterToken"];
[self.twitterClient setAccessToken:twitterToken];
[self.twitterClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self.twitterClient getPath:#"statuses/home_timeline.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *responseArray = (NSArray *)responseObject;
[tweets addObjectsFromArray:responseArray];
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}

UITableView Exception iOS

I am not able to figure out what is causing the application crash. A UITableView is being filled with data using the method numberOfRowsInSection. The first two record loads correctly but when the 3rd row is about to load, the app crashes. Please help.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
myDictionary = self.myArray;
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [myDictionary count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TransHistoryCell";
TransHistoryCell *cell = (TransHistoryCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
#try
{
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TransHistoryCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSDictionary *currentDictionary = [myDictionary objectAtIndex:indexPath.row];
for(NSDictionary *object in currentDictionary)
{
NSString *key = [object valueForKey:#"Key"];
NSString *value = [object valueForKey:#"Value"];
if([key isEqualToString:DATE])
{
cell.dateLabel.text = value;
}
else if([key isEqualToString:TRANSACTION_ID])
{
cell.transactionIdLabel.text = value;
}
else if([key isEqualToString:THIRD_PARTY])
{
cell.thirdPartyLabel.text = value;
}
else if([key isEqualToString:AMOUNT])
{
cell.amountLabel.text = value;
}
else if([key isEqualToString:TRANSACTION_DESC])
{
cell.transactionDescLabel.text = value;
}
}
}
#catch (NSException *exception)
{
NSLog(#"Exception: %#", exception);
}
#finally
{
return cell;
}
}
Exception:
2015-01-14 09:49:12.808 MobileProject[19580:5974561] -[NSNull length]: unrecognized selector sent to instance 0x103796ce0
2015-01-14 09:49:12.812 MobileProject
[19580:5974561] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 0x103796ce0'
*** First throw call stack:
(
0 CoreFoundation 0x00000001034edf35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000102187bb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001034f504d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010344d27c ___forwarding___ + 988
4 CoreFoundation 0x000000010344ce18 _CF_forwarding_prep_0 + 120
5 UIKit 0x00000001009b2f45 -[UILabel _textRectForBounds:limitedToNumberOfLines:includingShadow:] + 65
6 UIKit 0x00000001009b2da0 -[UILabel textRectForBounds:limitedToNumberOfLines:] + 76
7 UIKit 0x00000001009b6852 -[UILabel _intrinsicSizeWithinSize:] + 170
8 UIKit 0x00000001009b6932 -[UILabel intrinsicContentSize] + 76
9 UIKit 0x0000000100e6cea4 -[UIView(UIConstraintBasedLayout) _generateContentSizeConstraints] + 33
10 UIKit 0x0000000100e6cc64 -[UIView(UIConstraintBasedLayout) _updateContentSizeConstraints] + 422
11 UIKit 0x0000000100e740d6 -[UIView(AdditionalLayoutSupport) updateConstraints] + 163
12 UIKit 0x00000001009b679d -[UILabel updateConstraints] + 272
13 UIKit 0x0000000100e736fa -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 248
14 UIKit 0x0000000100e738f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
15 CoreFoundation 0x00000001033f6194 CFArrayApplyFunction + 68
16 UIKit 0x0000000100e7369b -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
17 Foundation 0x0000000101aead6e -[NSISEngine withBehaviors:performModifications:] + 155
18 UIKit 0x0000000100e738f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
19 CoreFoundation 0x00000001033f6194 CFArrayApplyFunction + 68
20 UIKit 0x0000000100e7369b -[UIView(AdditionalLayoutSupport) _internalUpdateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 153
21 UIKit 0x0000000100e738f2 -[UIView(AdditionalLayoutSupport) _updateConstraintsIfNeededAccumulatingViewsNeedingSecondPassAndViewsNeedingBaselineUpdate:] + 124
22 UIKit 0x0000000100e73dbe __60-[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded]_block_invoke + 96
23 UIKit 0x0000000100e73a86 -[UIView(AdditionalLayoutSupport) updateConstraintsIfNeeded] + 231
24 UIKit 0x0000000100c698b8 -[UITableViewCellContentView updateConstraintsIfNeeded] + 95
25 UIKit 0x0000000100e7419e -[UIView(AdditionalLayoutSupport) _updateConstraintsAtEngineLevelIfNeeded] + 159
26 UIKit 0x000000010085ab2d -[UIView(Hierarchy) _updateConstraintsAsNecessaryAndApplyLayoutFromEngine] + 114
27 UIKit 0x0000000100866973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
28 QuartzCore 0x0000000103d6ade8 -[CALayer layoutSublayers] + 150
29 QuartzCore 0x0000000103d5fa0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
30 QuartzCore 0x0000000103d5f87e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
31 QuartzCore 0x0000000103ccd63e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
32 QuartzCore 0x0000000103cce74a _ZN2CA11Transaction6commitEv + 390
33 QuartzCore 0x0000000103ccedb5 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
34 CoreFoundation 0x0000000103422dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
35 CoreFoundation 0x0000000103422d20 __CFRunLoopDoObservers + 368
36 CoreFoundation 0x0000000103418b53 __CFRunLoopRun + 1123
37 CoreFoundation 0x0000000103418486 CFRunLoopRunSpecific + 470
38 GraphicsServices 0x000000010338b9f0 GSEventRunModal + 161
39 UIKit 0x00000001007ed420 UIApplicationMain + 1282
40 MobileProject 0x0000000100535c83 main + 115
41 libdyld.dylib 0x0000000107323145 start + 1
42 ??? 0x0000000000000002 0x0 + 2
)
libc++abi.dylib: terminating with uncaught exception of type NSException
you are trying to get the length of what you think is an NSString but is actually NSNull. so check the NSNULL value in both key's ` Key and value

'NSInvalidArgumentException', reason: '-[__NSSetI getDataInBackgroundWithBlock:]

Please help me with my school project, currently i suppose to retrieve a set of record from the database and display the record based on their category.
I am new to IOS programming so please help me.
If possible please explain to me what is my mistake and possible solution to solve it.
Sorry to be rude, i need the solution to solve it as soon as possible cause i also need to work on other part of the project.
LocationListTableViewController.m
#import "LocationListTableViewController.h"
#import <Parse/Parse.h>
#interface LocationListTableViewController ()
#property (strong, nonatomic) IBOutlet UITableView *testView;
#end
#implementation LocationListTableViewController {
NSArray *storeLocation;
NSMutableDictionary *categoriesDict;
NSString *checkValue;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
PFQuery *query = [PFQuery queryWithClassName:#"GPS"];
// pulling everything
UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
ai.center = self.view.center;
[ai startAnimating];
[self.view addSubview:ai];
storeLocation = [query findObjects];
[ai stopAnimating];
[self.tableView reloadData];
categoriesDict = [[NSMutableDictionary alloc]init];
for (NSDictionary *locationCat in storeLocation) {
NSString *stringLocation = [locationCat objectForKey:#"locationCategory"];
NSMutableSet *categoriesSet = [categoriesDict objectForKey:stringLocation];
if (!categoriesSet)
{
categoriesSet = [NSMutableSet set];
[categoriesDict setObject:categoriesSet forKey:[locationCat objectForKey:#"locationCategory"]];
}
[categoriesSet addObject:locationCat];
// NSLog(#"categroesDict value are %d", [[categoriesDict objectForKey:#"All"] count]);
// NSLog(#"categroesDict value are %#", [categoriesDict objectForKey:#"test"]);
};
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[categoriesDict objectForKey:checkValue] count];
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleid = #"Location";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleid];
if (cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:simpleid];
}
// NSLog(#"categoriesDict objectForKey:checkValue ---- %#", [categoriesDict objectForKey:checkValue]);
// NSLog(#"categoriesDict objectForKey:checkValue valueForKey ---- %#", [[categoriesDict objectForKey:checkValue]valueForKey:#"locationCategory"]);
// NSLog(#"categoriesDict objectForKey:checkValue valueForKey ---- %#", [[categoriesDict objectForKey:checkValue]valueForKey:#"locationName"]);
UILabel *locationLabel = (UILabel *)[cell viewWithTag:100];
locationLabel.text = [[categoriesDict objectForKey:checkValue]valueForKey:#"locationName"];
UILabel *addressLabel = (UILabel *)[cell viewWithTag:101];
addressLabel.text = [[categoriesDict objectForKey:checkValue]valueForKey:#"locationAddress"];
UIImageView *thumbnailImageView = (PFImageView *)[cell viewWithTag:102];
self.thumbnail= [[categoriesDict objectForKey:checkValue]valueForKey:#"locationImage"];
// NSLog(#"thumbnail is %#", self.thumbnail);
if (self.thumbnail == NULL)
{
thumbnailImageView.image= [UIImage imageNamed:#"placeholder.jpg"];
} else
{
//Got error occurred
[self.thumbnail getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
if (!error) {
UIImage *image = [UIImage imageWithData:imageData];
thumbnailImageView.image = image;
}
else{
NSLog(#"imageData value; %#", imageData);
}
}];
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [categoriesDict count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
checkValue = [[categoriesDict allKeys]objectAtIndex:section];
return [[categoriesDict allKeys]objectAtIndex:section];
}
#end
Error Message
2015-01-14 15:27:36.658 MyLocationDemo[5591:60b] Warning: A long-running operation is being executed on the main thread.
Break on warnBlockingOperationOnMainThread() to debug.
2015-01-14 15:28:04.207 MyLocationDemo[5591:60b] -[__NSSetI getDataInBackgroundWithBlock:]: unrecognized selector sent to instance 0xaabed00
2015-01-14 15:28:04.208 MyLocationDemo[5591:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSSetI getDataInBackgroundWithBlock:]: unrecognized selector sent to instance 0xaabed00'
*** First throw call stack:
(
0 CoreFoundation 0x027711e4 __exceptionPreprocess + 180
1 libobjc.A.dylib 0x024f08e5 objc_exception_throw + 44
2 CoreFoundation 0x0280e243 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3 CoreFoundation 0x0276150b ___forwarding___ + 1019
4 CoreFoundation 0x027610ee _CF_forwarding_prep_0 + 14
5 MyLocationDemo 0x000030df -[LocationListTableViewController tableView:cellForRowAtIndexPath:] + 1199
6 UIKit 0x012a911f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
7 UIKit 0x012a91f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
8 UIKit 0x0128aece -[UITableView _updateVisibleCellsNow:] + 2428
9 UIKit 0x0129f6a5 -[UITableView layoutSubviews] + 213
10 UIKit 0x0121f964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
11 libobjc.A.dylib 0x0250282b -[NSObject performSelector:withObject:] + 70
12 QuartzCore 0x004ee45a -[CALayer layoutSublayers] + 148
13 QuartzCore 0x004e2244 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
14 QuartzCore 0x004e20b0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
15 QuartzCore 0x004487fa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
16 QuartzCore 0x00449b85 _ZN2CA11Transaction6commitEv + 393
17 QuartzCore 0x005075b0 +[CATransaction flush] + 52
18 UIKit 0x011ae9bb _UIApplicationHandleEventQueue + 13095
19 CoreFoundation 0x026fa77f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
20 CoreFoundation 0x026fa10b __CFRunLoopDoSources0 + 235
21 CoreFoundation 0x027171ae __CFRunLoopRun + 910
22 CoreFoundation 0x027169d3 CFRunLoopRunSpecific + 467
23 CoreFoundation 0x027167eb CFRunLoopRunInMode + 123
24 GraphicsServices 0x043555ee GSEventRunModal + 192
25 GraphicsServices 0x0435542b GSEventRun + 104
26 UIKit 0x011b0f9b UIApplicationMain + 1225
27 MyLocationDemo 0x0000391d main + 141
28 libdyld.dylib 0x02cba701 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

[LoginViewController viewControllers]: unrecognized selector sent to instance 0x10942c3d0

Help!
I am new to XCode and now i am facing a problem.
When i use the following code in the app and create a new ViewController class LoginViewController.
In iPhone, the app work great. But when I test in iPad it crash and display the following content in the log:
2014-05-06 17:05:31.289 We Love HK[38711:60b] -[LoginViewController viewControllers]: unrecognized selector sent to instance 0x10942c3d0
2014-05-06 17:05:31.291 We Love HK[38711:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LoginViewController viewControllers]: unrecognized selector sent to instance 0x10942c3d0'
*** First throw call stack:
(
0 CoreFoundation 0x00000001019fc495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010175b99e objc_exception_throw + 43
2 CoreFoundation 0x0000000101a8d65d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00000001019edd8d ___forwarding___ + 973
4 CoreFoundation 0x00000001019ed938 _CF_forwarding_prep_0 + 120
5 We Love HK 0x0000000100001086 -[AppDelegate application:didFinishLaunchingWithOptions:] + 246
6 UIKit 0x00000001003033d9 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 264
7 UIKit 0x0000000100303be1 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1605
8 UIKit 0x0000000100307a0c -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 660
9 UIKit 0x0000000100318d4c -[UIApplication handleEvent:withNewEvent:] + 3189
10 UIKit 0x0000000100319216 -[UIApplication sendEvent:] + 79
11 UIKit 0x0000000100309086 _UIApplicationHandleEvent + 578
12 GraphicsServices 0x0000000103b2b71a _PurpleEventCallback + 762
13 GraphicsServices 0x0000000103b2b1e1 PurpleEventCallback + 35
14 CoreFoundation 0x000000010197e679 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
15 CoreFoundation 0x000000010197e44e __CFRunLoopDoSource1 + 478
16 CoreFoundation 0x00000001019a7903 __CFRunLoopRun + 1939
17 CoreFoundation 0x00000001019a6d83 CFRunLoopRunSpecific + 467
18 UIKit 0x00000001003072e1 -[UIApplication _run] + 609
19 UIKit 0x0000000100308e33 UIApplicationMain + 1010
20 We Love HK 0x00000001000044b3 main + 115
21 libdyld.dylib 0x000000010207f5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
And LoginViewController.h:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "KeychainItemWrapper.h"
#import Security;
#interface LoginViewController : UIViewController <UITextFieldDelegate>
#property (nonatomic, retain) IBOutlet UILabel *version_label;
#property (strong, nonatomic) IBOutlet UITextField *txtUsername;
#property (strong, nonatomic) IBOutlet UITextField *txtPassword;
- (IBAction) loginClicker:(id)sender;
- (IBAction) backgroundTap:(id)sender;
- (IBAction) keyboardDismiss: (id) sender;
- (IBAction) click_exit: (id) sender;
#end
LoginViewController.m:
#import "LoginViewController.h"
#implementation LoginViewController;
#synthesize version_label;
#synthesize txtUsername;
#synthesize txtPassword;
-(void)viewDidLoad
{
KeychainItemWrapper *keychainWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:#"UserAuthToken" accessGroup:nil];
NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"]; // Get App Version
NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleVersion"]; // Get App Build Number
version_label.numberOfLines = 0; // Enable \n break line
version_label.hidden = NO; // Disable Hidden
//[keychainWrapper resetKeychainItem];
version_label.text = [NSString stringWithFormat:#"V %# (Build %#)", version, build]; // Change Version Label's Content
if ([keychainWrapper objectForKey:(__bridge id)(kSecAttrAccount)] && [keychainWrapper objectForKey:(__bridge id)(kSecValueData)]){
txtUsername.text = [keychainWrapper objectForKey:(__bridge id)(kSecAttrAccount)];
txtPassword.text = [keychainWrapper objectForKey:(__bridge id)(kSecValueData)];
}
}
-(IBAction) keyboardDismiss: (id) sender{
[txtUsername resignFirstResponder];
[txtPassword resignFirstResponder];
}
- (IBAction)backgroundTap:(id)sender {
[txtUsername resignFirstResponder];
[txtPassword resignFirstResponder];
}
- (IBAction)click_exit:(id)sender {
//[txtUsername resignFirstResponder];
//[txtPassword resignFirstResponder];
}
- (IBAction)loginClicker:(id)sender {
NSInteger success = 0;
#try {
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"請輸入帳號及密碼!" :#"登入失敗!" :0];
} else {
KeychainItemWrapper *keychainWrapper = [[KeychainItemWrapper alloc] initWithIdentifier:#"UserAuthToken" accessGroup:nil];
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[self.txtUsername text],[self.txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://ls.arefly.com/other/php/welovehk/login.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"login_status"] integerValue];
NSLog(#"Success: %ld", (long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[keychainWrapper setObject:[self.txtUsername text] forKey:(__bridge id)(kSecAttrAccount)];
[keychainWrapper setObject:[self.txtPassword text] forKey:(__bridge id)(kSecValueData)];
NSString *name_msg = (NSString *) jsonData[#"name_msg"];
[self alertStatus:name_msg :#"歡迎!" :0];
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"登入失敗!" :0];
txtPassword.text = #"";
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"登入失敗!" :0];
txtPassword.text = #"";
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"登入失敗!" :#"錯誤:" :0];
txtPassword.text = #"";
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
#end
and here also didFinishLaunchingWithOptions in AppDelegate.m (but i do not think i change anything of it):
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
splitViewController.delegate = (id)navigationController.topViewController;
}
return YES;
}
and here is my Main_iPad.storyboard:
http://uploadpie.com/rTIVc
and here is my Main_iPhone.storyboard:
http://uploadpie.com/gmpms
Can any one help me?
Thanks!
UPDATE
After i comment the whole if block in -(BOOL)application:didFinishLaunchingWithOptions:, its become ok and do not crash.
But there are other crash appear when i want to do [self performSegueWithIdentifier:#"login_success" sender:self];
2014-05-06 18:55:28.839 We Love HK[45660:60b] Success: 1
2014-05-06 18:55:28.839 We Love HK[45660:60b] Login SUCCESS
2014-05-06 18:55:28.887 We Love HK[45660:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a Split View Controllers modally <LoginViewController: 0x109429ca0>.'
*** First throw call stack:
(
0 CoreFoundation 0x00000001019fc495 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010175b99e objc_exception_throw + 43
2 UIKit 0x0000000100408c93 -[UIViewController presentViewController:withTransition:completion:] + 4027
3 We Love HK 0x0000000100005a35 -[LoginViewController loginClicker:] + 3813
4 UIKit 0x0000000100309f06 -[UIApplication sendAction:to:from:forEvent:] + 80
5 UIKit 0x0000000100309eb4 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 17
6 UIKit 0x00000001003e6880 -[UIControl _sendActionsForEvents:withEvent:] + 203
7 UIKit 0x00000001003e595d -[UIControl touchesBegan:withEvent:] + 219
8 UIKit 0x0000000100340b74 -[UIWindow _sendTouchesForEvent:] + 300
9 UIKit 0x00000001003416e4 -[UIWindow sendEvent:] + 925
10 UIKit 0x000000010031929a -[UIApplication sendEvent:] + 211
11 UIKit 0x0000000100306aed _UIApplicationHandleEventQueue + 9579
12 CoreFoundation 0x000000010198bd21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
13 CoreFoundation 0x000000010198b5f2 __CFRunLoopDoSources0 + 242
14 CoreFoundation 0x00000001019a746f __CFRunLoopRun + 767
15 CoreFoundation 0x00000001019a6d83 CFRunLoopRunSpecific + 467
16 GraphicsServices 0x0000000103b29f04 GSEventRunModal + 161
17 UIKit 0x0000000100308e33 UIApplicationMain + 1010
18 We Love HK 0x00000001000045b3 main + 115
19 libdyld.dylib 0x000000010207f5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Also i want to know how can i set the splitViewController.delegate from a different place?
You should propably share your application:didFinishLaunchingWithOptions: method.
I am pretty sure that somewhere there you are using LoginViewController is used as UINavigationController or UISplitViewController. That is why viewControllers method is called there.
According to your application:didFinishLaunchingWithOptions method, it crashes here
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
Probably you have wrong InitialViewController in your iPad storyboard
The exception clearly states that
[LoginViewController viewControllers]: unrecognized selector sent to
instance
mean, the controller which is not present in the UIStoryBoard of iPad.
their will be 2 storyBoards in the project,
In iPhone, the app work great.
So mean, you have created LoginViewController for only iPhone not for iPad's storyBoard.
you need to create the LoginViewController in the iPad storyBoard as well.

Resources