Issue Paging Twitter with AFNetworking - ios

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);
}];
}

Related

Application crashes when type a letter in search bar

enter image description hereHere i have implemented all the things require for using search bar but don't know whats going wrong with the app. it crashes when i start entering anything in search bar. Any help is appreciated.
Error :
'Can't use in/contains operator with collection <NSManagedObject: 0x7fa1c24d32a0> (entity: Personal; id: 0xd0000000000c0000 <x-coredata://2C964E4A-A8CD-465B-BB23-0121B7C7EEFB/Personal/p3> ; data: {
attribute = Ios;
name = man;
}) (not a collection)'
*** First throw call stack:
(
0 CoreFoundation 0x0000000104ed5e65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001045c2deb objc_exception_throw + 48
2 Foundation 0x00000001041db6b1 -[NSCompoundPredicate evaluateWithObject:substitutionVariables:] + 0
3 Foundation 0x00000001041b2719 -[NSPredicateOperator performOperationUsingObject:andObject:] + 286
4 Foundation 0x00000001041b1e3c -[NSComparisonPredicate evaluateWithObject:substitutionVariables:] + 313
5 Foundation 0x00000001041b1c94 _filterObjectsUsingPredicate + 398
6 Foundation 0x00000001041b1a84 -[NSArray(NSPredicateSupport) filteredArrayUsingPredicate:] + 279
7 Personal Data 0x00000001040ba6a2 -[ViewDetailViewController updateSearchResultsForSearchController:] + 514
8 UIKit 0x0000000105cb2185 -[UISearchController _searchBar:textDidChange:] + 102
9 UIKit 0x0000000105675d47 -[UISearchBar(UISearchBarStatic) _searchFieldEditingChanged] + 360
10 UIKit 0x0000000105285194 -[UIApplication sendAction:to:from:forEvent:] + 92
11 UIKit 0x00000001053f46fc -[UIControl sendAction:to:forEvent:] + 67
12 UIKit 0x00000001053f49c8 -[UIControl _sendActionsForEvents:withEvent:] + 311
13 UIKit 0x0000000105c68a85 -[UITextField fieldEditorDidChange:] + 206
14 UIKit 0x0000000105c73cb7 -[UITextInputController _sendDelegateChangeNotificationsForText:selection:] + 138
15 UIKit 0x0000000105c76281 -[UITextInputController _insertText:fromKeyboard:] + 893
16 UIKit 0x0000000105c76bcd -[UITextInputController insertText:] + 365
17 UIKit 0x0000000105400728 -[UIFieldEditor insertFilteredText:] + 800
18 UIKit 0x0000000105c6d7d7 -[UITextField insertFilteredText:] + 103
19 UIKit 0x000000010552ba83 -[UIKeyboardImpl insertText:] + 125
20 UIKit 0x0000000105528278 -[UIKeyboardImpl performKeyboardOutput:] + 496
21 UIKit 0x0000000105527e65 __55-[UIKeyboardImpl handleKeyboardInput:executionContext:]_block_invoke_2 + 164
22 UIKit 0x0000000105c96724 -[UIKeyboardTaskQueue continueExecutionOnMainThread] + 332
23 Foundation 0x00000001041aa067 __NSThreadPerformPerform + 283
24 CoreFoundation 0x0000000104e01a31 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
25 CoreFoundation 0x0000000104df795c __CFRunLoopDoSources0 + 556
26 CoreFoundation 0x0000000104df6e13 __CFRunLoopRun + 867
27 CoreFoundation 0x0000000104df6828 CFRunLoopRunSpecific + 488
28 GraphicsServices 0x00000001086f0ad2 GSEventRunModal + 161
29 UIKit 0x0000000105283610 UIApplicationMain + 171
30 Personal Data 0x00000001040bbd9f main + 111
31 libdyld.dylib 0x000000010762992d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
#import "ViewDetailViewController.h"
#import <CoreData/CoreData.h>
#interface ViewDetailViewController () <UITableViewDelegate,UITableViewDataSource>
{
NSMutableArray *_park;
}
#property (nonatomic, strong) NSMutableArray *searchResult;
#end
#implementation ViewDetailViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Personal"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
Search Bar Declaration
[self.tableView reloadData];
// self.searchResult = [NSMutableArray arrayWithCapacity: [self.devices count]];
searchResultsArray = [[NSArray alloc]init];
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
self.searchController.searchBar.delegate = self;
self.searchController.searchResultsUpdater = self;
[self.searchController.searchBar sizeToFit];
self.searchController.dimsBackgroundDuringPresentation = NO;
self.definesPresentationContext = YES;
self.tableView.tableHeaderView = self.searchController.searchBar;
// Do any additional setup after loading the view.
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
NSString *searchString = self.searchController.searchBar.text;
if (searchString.length > 0)
{
NSPredicate *resultPredicate;
NSInteger scope = self.searchController.searchBar.selectedScopeButtonIndex;
if(scope == 0){
resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",searchString];
}else{
resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",searchString];
}
NSArray * filterArray = [self.devices filteredArrayUsingPredicate:resultPredicate];
_park = [[NSMutableArray alloc] init];
[_park addObject:filterArray];
}
else{
//_park = (NSMutableArray *)shortedArray;
}
[self.tableView reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
[self updateSearchResultsForSearchController:self.searchController];
}
TableView delegate methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.devices count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
// cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%#", [device valueForKey:#"name"]]];
[cell.detailTextLabel setText:[device valueForKey:#"attribute"]];
return cell;
}
}
Try this, use attribute name with SELF. I am assuming the objects are of type Personal with attributes name and other.
NSPredicate *resultPredicate;
NSInteger scope = self.searchController.searchBar.selectedScopeButtonIndex;
if(scope == 0){
resultPredicate = [NSPredicate predicateWithFormat:#"(SELF.name contains[cd] %#) OR (SELF.other CONTAINS[cd] %#)",searchString, searchString];
}else{
resultPredicate = [NSPredicate predicateWithFormat:#"SELF.name contains[cd] %#",searchString];
}
NSArray * filterArray = [self.devices filteredArrayUsingPredicate:resultPredicate];
_park = [[NSMutableArray alloc] init];
[_park addObject:filterArray];

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

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];

Parsing RSS in Obj-C?

I'm trying to parse RSS date to view in my app, following this tutorial. I have a JSON file to retrieve information from and display on the screen.
Here's the code
//
// ViewController.m
// JSONyt
//
// Created by yo_291 on 3/16/15.
// Copyright (c) 2015 yo_291. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[[self myView]setDelegate:self];
[[self myView]setDataSource:self];
array = [[NSMutableArray alloc]init];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *rd = [allDataDictionary objectForKey:#"responseData"];
NSDictionary *feed = [rd objectForKey:#"feed"];
NSArray *aoe = [feed objectForKey:#"entries"];
for(NSDictionary *diction in aoe)
{
NSDictionary *numb = [diction objectForKey:#"0"];
NSString *title = [numb objectForKey:#"title"];
[array addObject:title];
}
[[self myView] reloadData];
}
- (IBAction)getFeed:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://ajax.googleapis.com/ajax/services/feed/load?v=2.0&q=http://www.britannica.com/feeds/tdih.rss&num="];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData = [[NSMutableData alloc]init];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellI = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellI];
if(!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellI];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
#end
The application crashes on the line [array addObject:title];.
Error Stack trace:
2015-03-16 22:32:51.650 JSONyt[8195:547408] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(
0 CoreFoundation 0x000000010ba28a75 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010b6c1bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010b8f70ca -[__NSArrayM insertObject:atIndex:] + 954
3 JSONyt 0x000000010b18da5f -[ViewController connectionDidFinishLoading:] + 735
4 CFNetwork 0x000000010d85998c __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke + 69
5 CFNetwork 0x000000010d859930 -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] + 199
6 CFNetwork 0x000000010d859a97 -[NSURLConnectionInternal _withActiveConnectionAndDelegate:] + 48
7 CFNetwork 0x000000010d729937 ___ZN27URLConnectionClient_Classic26_delegate_didFinishLoadingEU13block_pointerFvvE_block_invoke + 107
8 CFNetwork 0x000000010d7f6a31 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 273
9 CFNetwork 0x000000010d714d16 _ZN19RunloopBlockContext13_invoke_blockEPKvPv + 72
10 CoreFoundation 0x000000010b930b44 CFArrayApplyFunction + 68
11 CFNetwork 0x000000010d714bd7 _ZN19RunloopBlockContext7performEv + 133
12 CFNetwork 0x000000010d714a16 _ZN17MultiplexerSource7performEv + 256
13 CFNetwork 0x000000010d71482c _ZN17MultiplexerSource8_performEPv + 72
14 CoreFoundation 0x000000010b95dc91 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
15 CoreFoundation 0x000000010b953b5d __CFRunLoopDoSources0 + 269
16 CoreFoundation 0x000000010b953194 __CFRunLoopRun + 868
17 CoreFoundation 0x000000010b952bc6 CFRunLoopRunSpecific + 470
18 GraphicsServices 0x000000010f005a58 GSEventRunModal + 161
19 UIKit 0x000000010be18580 UIApplicationMain + 1282
20 JSONyt 0x000000010b18e483 main + 115
21 libdyld.dylib 0x000000010dfd6145 start + 1
22 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
but I have no idea how to go about fixing it. To my eyes I'm searching the JSON file correctly but I may be wrong. The JSON file is also an RSS feed that I've used a google tool to "turn" into a JSON database, so I'm unsure if complications are from there.
Let me know any/all information that is needed, this is my first post so I don't know if I'm delivering enough context.
The error indicates that the object to be inserted is nil. The problem lies in the following lines:
NSDictionary *numb = [diction objectForKey:#"0"];
NSString *title = [numb objectForKey:#"title"];
[array addObject:title];
You never check whether title is nil or not before adding object to array. You can always use NSLog() to debug the values and check for nil values using techniques similar as follow:
if([numb objectForKey:#"title"] != nil) {
[array addObject:[numb objectForKey:#"title"]];
}
p.s. assigning the value to title is useless, as the title just used once (wasting memory).
Also, using libraries like AFNetworking will make your codes simpler, and provides extra error handling.

'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