Twitter number of followers iOS 6 - objective-c

Hi how can I get the number of followers of the current twitter user in iOS 6. The TWRequest is depreciated so how can I use the new Social.Framework to get the number of followers?

First, you need to Authenticate your request (Get permission).
second, see follow these steps:
1.Download FHSTwitterEngine Twitter Library.
2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".
3.add SystemConfiguration.framework to your project.
Usage : 1.in the [ViewDidLoad] add the following code:
UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
logIn.frame = CGRectMake(100, 100, 100, 100);
[logIn setTitle:#"Login" forState:UIControlStateNormal];
[logIn addTarget:self action:#selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:logIn];
[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:#"<consumer_key>" andSecret:#"<consumer_secret>"];
[[FHSTwitterEngine sharedEngine]setDelegate:self];
and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.
you need to get the permission for your request, with the following method which will present Login window:
- (void)showLoginWindow:(id)sender {
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
}];
}
when the Login window is presented, enter your Twitter Username and Password to authenticate your request.
add the following methods to your code:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[FHSTwitterEngine sharedEngine]loadAccessToken];
NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
if (username.length > 0) {
lbl.text = [NSString stringWithFormat:#"Logged in as %#",username];
[self listResults];
} else {
lbl.text = #"You are not logged in.";
}
}
- (void)storeAccessToken:(NSString *)accessToken {
[[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:#"SavedAccessHTTPBody"];
}
- (NSString *)loadAccessToken {
return [[NSUserDefaults standardUserDefaults]objectForKey:#"SavedAccessHTTPBody"];
}
4.Now you are ready to get your request, the following method will list your followers ID's, add them to an NSArray and the get the Count from the NSArray:
- (Void)listFriends:(id)sender {
NSMutableArray *arr = [[NSMutableArray alloc]init];
[_tweetField resignFirstResponder];
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// NSLog(#"Friends' IDs: %#",[[FHSTwitterEngine sharedEngine]getFriendsIDs]);
dict = [[FHSTwitterEngine sharedEngine]getFollowersIDs];
for (NSDictionary *item in [dict objectForKey:#"ids"]) {
[arr addObject:[dict objectForKey:#"ids"]];
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"====> %d",[arr count]);
}
});
}
});
}
I tested this code and it's working perfectly ^_^.

use This code
(IBAction)listFriends:(id)sender {
NSMutableArray *arr = [[NSMutableArray alloc]init];
dict=[[NSMutableDictionary alloc]init];
[_tweetField resignFirstResponder];
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//to get friends id.......
NSLog(#"Friends' IDs: %#",[[FHSTwitterEngine sharedEngine]getFriendsIDs]);
/* dict = [[FHSTwitterEngine sharedEngine]getFollowersIDs];
for (NSDictionary *item in [dict objectForKey:#"ids"]) {
[arr addObject:[dict objectForKey:#"ids"]];
}*/
// To get friends name ...
// NSLog(#"Friends_Name: %#",[[FHSTwitterEngine sharedEngine]listFriendsForUser:_loggedInUserLabel.text isID:NO withCursor:#"-1"]);
dict = [[FHSTwitterEngine sharedEngine]listFriendsForUser:_loggedInUserLabel.text isID:NO withCursor:#"-1"];
NSLog(#"====> %#",[dict objectForKey:#"users"] );
NSMutableArray *array=[dict objectForKey:#"users"];
for(int i=0;i<[array count];i++)
{
NSLog(#"names:%#",[[array objectAtIndex:i]objectForKey:#"name"]);
}
// NSLog(#"Friends_Name: %#",[[FHSTwitterEngine sharedEngine]getMentionsTimelineWithCount:1000 sinceID:nil maxID:nil]);
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Complete!" message:#"Your list of followers has been fetched" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// NSLog(#"====> %d",[arr count]);
}
});
}
});
}

Related

Why is my Progress HUD not displaying as expected

I'm trying to develop a 'passwordless' registration form using a QRCode. The background processing works (can authenticate user), but noting happens visually until the registration is complete and the user is redirected to the apps main ViewController, however, A progress dialog with spinner is supposed to appear during the registration process but it doesn't. If, I manually input the credentials and press 'authenticate', everything works as expected, Just not after scanning the QR code.
Please see code below:
#interface ViewControllerRegister (){
JGProgressHUD *HUD;
NSString *regid;
NSString *regpin;
NSMutableDictionary *dicto;
}
//OPEN QRCODE READER VC
- (IBAction)scanAction:(id)sender
{
if ([QRCodeReader supportsMetadataObjectTypes:#[AVMetadataObjectTypeQRCode]]) {
static QRCodeReaderViewController *vc = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
QRCodeReader *reader = [QRCodeReader readerWithMetadataObjectTypes:#[AVMetadataObjectTypeQRCode]];
vc = [QRCodeReaderViewController readerWithCancelButtonTitle:#"Cancel" codeReader:reader startScanningAtLoad:YES];
vc.modalPresentationStyle = UIModalPresentationFormSheet;
});
vc.delegate = self;
[vc setCompletionWithBlock:^(NSString *resultAsString) {
// NSLog(#"Completion with result: %#", resultAsString);
}];
[self presentViewController:vc animated:YES completion:NULL];
}
else {
[self showAlert:#"Reader not supported by the current device"];
}
}
//// PARSE THE RETURNED QR CODE DATA
#pragma mark - QRCodeReader Delegate Methods
- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result
{
[self dismissViewControllerAnimated:YES completion:^{
NSURL *stringfromscan = [NSURL URLWithString:result];
dicto = [NSMutableDictionary new];
NSURLComponents *components = [NSURLComponents componentsWithURL:stringfromscan resolvingAgainstBaseURL:NO];
NSArray *queryItems = [components queryItems];
for (NSURLQueryItem *item in queryItems)
{
[dicto setObject:[item value] forKey:[item name]];
}
if ([result rangeOfString:#"eloq"].location == NSNotFound && [result rangeOfString:#"unique"].location == NSNotFound) {
[self showAlert:#"Looks like you've scanned an incorect QR code"];
} else {
self.TextViewUniqueID.text = [dicto objectForKey:#"uniqueid"];
self.TextViewPIN.text = [dicto objectForKey:#"password"];
double delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self authent];
});
}
}];
}
/// CREDENTIAL VALIDATION OF SORTS
- (void)authent{
NSLog(#"s UNIQUEID %#", self.TextViewUniqueID.text);
NSLog(#"PIN %#", self.TextViewPIN.text);
// [self resignFirstResponder];
int uniqueID = [self.TextViewUniqueID.text length];
int PIN = [self.TextViewPIN.text length];
if (uniqueID < 7 || PIN < 6){
UIAlertController* alert = [UIAlertController alertControllerWithTitle:#"Error!"
message:#"Your UniqueID or PIN is too short."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"Try Again" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[self clear];
}else{
/*
HUD WILL NOT DISPLAY AFTER READING QR CODE
*/
HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.textLabel.text = #"Authenticating";
[HUD showInView:self.view];
[self PostJson:self.TextViewUniqueID.text :self.TextViewPIN.text];
}
}

Remove all controls (subviews) in UITabBarViewController

I'm fairly new to ios programming and I encountered an issue lately. I'm trying to navigate to a selected tab of a tabbarviewcontroller programmatically. Upon entering that selected tab, remove all controls in it and repopulate it with different controls.
I managed to navigate to that selected tab programmatically, however, i'm unable to remove all the subviews.
Below are snippet of my codes..
- (IBAction)btnSave:(id)sender {
orthoPaedicInjuryTabBarViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"OrthoInjuryTabBarVC"];
orthoPaedicInjuryTabBarViewController.selectedIndex = 2;
[self presentViewController:orthoPaedicInjuryTabBarViewController animated:YES completion:nil];
self.alert = [[UIAlertView alloc] initWithTitle:#"Empty Field, Step3"
message: #"Please fill up the frequency of exercises"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[self.alert show];
}
- (void)viewWillAppear:(BOOL)animated {
Store *MyStore = [Store SharedStore];
OrthoInjury *orthoInjury = MyStore.orthoInjury;
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"dd-MM-yyyy"];
NSString *Dob = [format stringFromDate:orthoInjury.dateOfInjury];
self.lblDateOfInjury.text= Dob;
// Do any additional setup after loading the view, typically from a nib.
self.typeOfExercisesList = [Utility GetTypesOfExercisesList];
self.pickerViewTypesOfexercises.dataSource = self;
self.pickerViewTypesOfexercises.delegate = self;
TherapyPhases *therapyPhases = MyStore.therapyPhases;
self.tbxNumberOfWeeks.text = #(therapyPhases.durationWeeks).stringValue;
if([[orthoInjury.natureOfInjury uppercaseString] isEqualToString:[#"Repetitive Strain Injury" uppercaseString]])
{
NSArray *subArray = [self.view subviews];
if([subArray count] != 0) {
for(int i = 1 ; i < [subArray count] ; i++) {
[[subArray objectAtIndex:i] removeFromSuperview];
/*if ([[subArray objectAtIndex:i] isKindOfClass:[UILabel class]])
{
NSLog(#"%#",[[subArray objectAtIndex:i] text]);
}*/
}
}
}
}
Try below for removing the subviews:-
NSMutableArray *subVws=[self.tabBarController.view.subviews mutableCopy];
[subVws performSelector:#selector(removeFromSuperview)];

QuickBlox : GCDAsyncSocketErrorDomain error

I'm trying to Implement chat module in my app. I am successfully done with Login and Register process from Simple Chat Demo into my app. It also returns user array of offline and online users.
Now after successfully log in I am getting below log :-
error:
2012-12-07 14:50:07.056 App[5324:790b] QBChatService/xmppStreamDidConnect
2012-12-07 14:50:08.285 App[5324:790f] QBChatService/xmppStreamDidAuthenticate
2012-12-07 14:51:08.291 App[5324:711f] QBChatService/xmppStreamDidDisconnect, error=Error Domain=GCDAsyncSocketErrorDomain Code=7 "Socket closed by remote peer" UserInfo=0xb982330 {NSLocalizedDescription=Socket closed by remote peer}
And I'm not able to receive chat messages into my app.
Any suggestions ?
Edit :-
In my app, when login is done I am sending the login request to QuickBlox API
if(loginDone)
{
NSString *userName = [_textUsername.text stringByReplacingOccurrencesOfString:#"#" withString:#"_"];
NSString *userPass = [_textPassword.text stringByReplacingOccurrencesOfString:#"#" withString:#"_"];
// Authenticate user
[QBUsers logInWithUserLogin:userName password:userPass delegate:self context:userPass];
}
#pragma mark -
#pragma mark QBActionStatusDelegate
// QuickBlox API queries delegate
-(void)completedWithResult:(Result *)result context:(void *)contextInfo
{
// QuickBlox User authentication result
if([result isKindOfClass:[QBUUserLogInResult class]])
{
// Success result
if(result.success)
{
QBUUserLogInResult *res = (QBUUserLogInResult *)result;
// save current user
[[DataManager shared] setCurrentUser: res.user];
NSLog(#"%#",res.user);
[[[DataManager shared] currentUser] setPassword:(NSString *)contextInfo];
NSLog(#"%#",res.user);
// Login to Chat
[QBChat instance].delegate = self;
[[QBChat instance] loginWithUser:[[DataManager shared] currentUser]];
// Register as subscriber for Push Notifications
[QBMessages TRegisterSubscriptionWithDelegate:nil];
// send request for getting user's filelist
PagedRequest *pagedRequest = [[PagedRequest alloc] init];
[pagedRequest setPerPage:10];
[QBContent blobsWithPagedRequest:pagedRequest delegate:self];
[pagedRequest release];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Errors"
message:[result.errors description]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
alert.tag = 1;
//[alert show];
[alert release];
[HUD hide:YES];
[self AfterLoginController];
}
}
}
-(void)completedWithResult:(Result *)result
{
if([result isKindOfClass:[QBUUserLogInResult class]]) // QuickBlox User authentication result
{
// Success result
if(result.success)
{
// If we are authenticating through Twitter/Facebook - we use token as user's password for Chat module
[self completedWithResult:result context:[BaseService sharedService].token];
}
}
else if ([result isKindOfClass:[QBCBlobPagedResult class]])
{
// Success result
if(result.success){
QBCBlobPagedResult *res = (QBCBlobPagedResult *)result;
// Save user's filelist
[DataManager shared].fileList = [[res.blobs mutableCopy] autorelease];
AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[app startsendPresenceTimer];
[HUD hide:YES];
[self AfterLoginController];
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Errors"
message:[result.errors description]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles: nil];
alert.tag = 1;
//[alert show];
[alert release];
[HUD hide:YES];
[self AfterLoginController];
}
}
Now in AppDelegate :-
- (void) startsendPresenceTimer
{
[QBChat instance].delegate = self;
// send presence
if(self.sendPresenceTimer == nil)
{
self.sendPresenceTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(sendPresence) userInfo:nil
repeats:YES];
}
if (self.requesAllUsersTimer == nil)
{
self.requesAllUsersTimer= [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:#selector(updateUsers) userInfo:nil repeats:YES];
}
[self.requesAllUsersTimer fire];
}
// send presence
- (void)sendPresence{
// presence in QuickBlox Chat
[[QBChat instance] sendPresence];
// presence in QuickBlox
[QBUsers userWithExternalID:1 delegate:nil];
}
- (void)updateUsers
{
// Retrieve all users
PagedRequest* request = [[PagedRequest alloc] init];
request.perPage = 100; // 100 users
[QBUsers usersWithPagedRequest:request delegate:self];
[request release];
}
Do you send presence periodically? It need because Chat server must knows is you online or offline.
Look at QuickBlox Chat setup guide, lines
Keep in mind that QuickBlox it's simple XMPP chat, ...
Just write single line
[NSTimer scheduledTimerWithTimeInterval:30 target:[QBChat instance] selector:#selector(sendPresence) userInfo:nil repeats:YES];
Application will send presence every 30 seconds

iOS: Image Will Not Delete From Array

I'm working on an app that behaves like a photo gallery, and I'm implementing the option to have the user delete photos from their gallery. To accomplish this, I decided to place an invisible button over each picture. When the user hits an "Edit" button, the hidden delete buttons over each picture become active. I'm using the same IBOutlet over each of the hidden buttons for simplicity, and I've tagged each button appropriately in Interface Builder. When the user taps the button over the picture, an alert view appears asking if they really want to delete it. If they click yes, I call removeObjectAtIndex. Here is the code I'm using:
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(#"User Clicked Yes.");
[self.array removeObjectAtIndex: alertView.tag];
}
[self.user setObject:array forKey:#"images"];
}
The issue here is that when I click "Yes" in the alert view, nothing happens. However, if I tap on the image and click "Yes" a second time, the app crashes, and the debug states:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray removeObjectAtIndex:]: index (0) beyond bounds (0)' So, I'm not sure where to go from here, I'm still very new to programming and everything looks correct to me. Any help is much appreciated, thanks!
Here is how I add them into the array:
////start of saving////
- (void)viewWillAppear:(BOOL)animated
{
self.user = [NSUserDefaults standardUserDefaults];
self.array = [[self.user objectForKey:#"images"]mutableCopy];
while(self.array == nil)
{
[self.user setObject:[NSMutableArray arrayWithObject:#""] forKey:#"images"];
self.array = [[self.user objectForKey:#"images"]mutableCopy];
NSLog(#"%#",#"attempting to create an array to store the images in");
}
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
self.array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)]];
[self.array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView5.image)]];
[self.user setObject:self.array forKey:#"images"];
[user synchronize];
}
- (void)viewDidLoad
{
self.user = [NSUserDefaults standardUserDefaults];
NSLog(#"It is %#", self.user);
self.array = [[self.user objectForKey:#"images"]mutableCopy];
imageView.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:0]];
imageView2.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:1]];
imageView3.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:2]];
imageView4.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:3]];
imageView5.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:4]];
imageView6.image = [[UIImage alloc] initWithData:[self.array objectAtIndex:5]];
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
backToGalleryButton.hidden = YES;
tapToDeleteLabel.hidden = YES;
deleteButton1.hidden = YES;
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.user = nil;
}
////end of saving
///// shows the hidden and invisible "delete" button over each photo.
- (IBAction)editButtonPressed:(id)sender {
grabButton.hidden = YES;
editButton.hidden = YES;
backToGalleryButton.hidden = NO;
tapToDeleteLabel.hidden = NO;
deleteButton1.hidden = NO;
}
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(#"Sender is %#", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:#"Delete"
message:#"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:#"No"
otherButtonTitles:#"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(#"User Clicked Yes.");
NSLog(#"Array: %#, index: %d", self.array, alertView.tag);
[self.array removeObjectAtIndex: alertView.tag];
}
[self.user setObject:array forKey:#"images"];
}
#end
EDIT: This is the code I use to put the objects into the UIImageView from the users camera roll:
- (IBAction)grabImage {
self.imgPicker = [[UIImagePickerController alloc] init];
self.imgPicker.delegate = self;
self.imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
_popover = [[UIPopoverController alloc] initWithContentViewController:imgPicker];
[_popover presentPopoverFromRect:self.imageView.bounds inView:self.imageView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
else {
[self presentModalViewController:imgPicker animated:YES];
}
[self.imgPicker resignFirstResponder];
}
// Sets the image in the UIImageView
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
if (imageView.image == nil) {
imageView.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView2.image == nil) {
imageView2.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView3.image == nil) {
imageView3.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
if (imageView4.image == nil) {
imageView4.image = img;
[picker dismissModalViewControllerAnimated:YES];
[self.popover dismissPopoverAnimated:YES];
return;
}
}
When I added NSLog(#"Array: %#, index: %d", self.array, alertView.tag); just before removeAtIndex the console says 2012-04-03 18:39:39.066 AppName[1631:f803] Array: (null), index: 0. Could that be the cause? I'm not sure why it would be, I think the code looks fine.
Removing the image from the array is not the only step you have to take. Your code is correct for removing the image from the array, which is why you get image out of bounds the second time, but you also need to remove the image from the UI so the user can no longer delete an image that is not there.
There are many oddities with this code but I think the problem is that you are not calling super on your viewwillappear and viewdidload functions. I would get rid of your viewWillAppear method as it serves no purpose.

Why does the pushViewController stop working when I remove a UIAlertView

I outsourced some iPhone development and I am trying to make a simple change to the code, but it does not make any sense to me. I am hoping that someone can help me out. I would ask the original developer, but they just left for a week long vacation and I would prefer to not wait.
//
// SettingViewController.m
// FoodStorageManagement
//
// Created by Ryan McLaughlin on 10/20/11.
// Copyright 2011 Food Storage Management. All rights reserved.
//
#import "SettingViewController.h"
#import "MainViewController.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"
#import "XMLRPCConnection.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>
#implementation SettingViewController
#synthesize Obj_string,LoginState,hashkey,validuser,apikey,spinnerView;
-(id)init
{
[super init];
img_loginBg=[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"Loginpage.png"]];
img_loginBg.frame=CGRectMake(0, 0, 320, 460);
app=[[UIApplication sharedApplication]delegate];
UserIDtxt=[[UITextField alloc]initWithFrame:CGRectMake(150, 163, 160, 25)];
UserIDtxt.returnKeyType=UIReturnKeyDone;
UserIDtxt.backgroundColor=[UIColor clearColor];
//UserIDtxt.text=#"user";
UserIDtxt.delegate=self;
UserIDtxt.tag=1;
pwdText=[[UITextField alloc]initWithFrame:CGRectMake(150, 220, 160, 25)];
pwdText.backgroundColor=[UIColor clearColor];
//pwdText.text=#"123456";
pwdText.secureTextEntry=YES;
pwdText.returnKeyType=UIReturnKeyDone;
pwdText.delegate=self;
pwdText.tag=2;
btn_SignUp=[UIButton buttonWithType:UIButtonTypeCustom];
btn_SignUp.frame=CGRectMake(45, 335, 95, 35);
btn_SignUp.backgroundColor=[UIColor clearColor];
[btn_SignUp setTitle:#"" forState:UIControlStateNormal];
[btn_SignUp addTarget:self action:#selector(ClickOnSignUp) forControlEvents:UIControlEventTouchUpInside];
[btn_SignUp retain];
btn_LogIn=[UIButton buttonWithType:UIButtonTypeCustom];
btn_LogIn.frame=CGRectMake(175, 335, 95, 35);
btn_LogIn.backgroundColor=[UIColor clearColor];
[btn_LogIn setTitle:#"" forState:UIControlStateNormal];
[btn_LogIn addTarget:self action:#selector(ClickOnLogIn) forControlEvents:UIControlEventTouchUpInside];
[btn_LogIn retain];
NSString *deviceVersion=[UIDevice currentDevice].systemVersion;
NSLog(#"%#",deviceVersion);
btn_Back=[UIButton buttonWithType:UIButtonTypeCustom];
btn_Back.frame=CGRectMake(8, 417, 50, 40);
btn_Back.backgroundColor=[UIColor clearColor];
[btn_Back setTitle:#"" forState:UIControlStateNormal];
[btn_Back addTarget:self action:#selector(ClickOnBack) forControlEvents:UIControlEventTouchUpInside];
[btn_Back retain];
return self;
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
[super loadView];
[self.view addSubview:img_loginBg];
[self.view addSubview:btn_SignUp];
[self.view addSubview:btn_LogIn];
[self.view addSubview:btn_Back];
[self.view addSubview:UserIDtxt];
[self.view addSubview:pwdText];
}
-(void)ClickOnSignUp
{
Connection=[[NetworkConnection alloc]initConnection];
if (Connection.isReachable)
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://www.foodstoragemanagement.com/signup.php"]];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Network Connection unavailable.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
-(void) startSpinner:(NSString*)type andDisplay:(NSString*)display{
//remove any existing spinners at this point
if(self.spinnerView)
{
[self.spinnerView.view removeFromSuperview];
self.spinnerView = nil;
}
self.spinnerView =[[[SpinnerModal alloc]initWithType:type andDisplay:display]autorelease];
//add this to the root view of the app
//ViewManager *viewMgr = [ViewManager getManager];
[self.view addSubview:self.spinnerView.view];
}
-(void) stopSpinner{
NSLog(#"SPINNER IS REMOVED");
[self.spinnerView.view removeFromSuperview];
self.spinnerView = nil;
}
-(void)ClickOnLogIn
{
Connection=[[NetworkConnection alloc]initConnection];
if (Connection.isReachable)
{
[self startSpinner:#"spinner" andDisplay:#"Loading"];
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:#selector(ClickOnLog) userInfo:nil repeats:NO];
}
else {
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Network Connection unavailable.." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
[self stopSpinner];
}
}
-(void)ClickOnLog
{
NSDate* now = [NSDate date];
NSString *dateString=[[NSString alloc]init];
dateString = [now description];
dateString=[self dateInFormat:#"%s"];
NSString *username=[UserIDtxt.text lowercaseString];
NSString *username_reverse=[username reverseString];
NSString *password_hash=[self sha256:pwdText.text];
NSString *str=[NSString stringWithFormat:#"%#%#%#",username,password_hash,dateString];
str=[self sha256:str];
app.username=[NSMutableString stringWithString:username];
app.password=[NSMutableString stringWithString:password_hash];
//url from plist
NSString *server=[[NSString alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
server=[plistDict objectForKey:#"NewUrl"];
XMLRPCRequest *reqHello = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[UserIDtxt.text lowercaseString] forKey:#"username"];
[dict setValue:str forKey:#"hash_key"];
[dict setValue:dateString forKey:#"timestamp"];
[reqHello setMethod:#"user.get_api" withObjects:[NSArray arrayWithObjects:dict,nil]];
NSString *result=[self executeXMLRPCRequest:reqHello];
if ([result length]>0)
{
NSLog(#"OUTPUT %#",result);
NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser1=[[NSXMLParser alloc]initWithData:data];
[parser1 setDelegate:self];
[parser1 parse];
[reqHello release];
defaults = [NSUserDefaults standardUserDefaults];
app.defaultuser=[NSUserDefaults standardUserDefaults];
[defaults setObject: app.globalApi_key forKey: #"api_key"];
[defaults setObject:UserIDtxt.text forKey:#"username"];
[defaults setObject:pwdText.text forKey:#"password"];
app.defaultuser=defaults;
if (!app.globalApi_key)
{
defaults = [NSUserDefaults standardUserDefaults];
}
[defaults synchronize];
if (!val)
{
val=[defaults objectForKey:#"api_key"];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"Unable to communicate with the server" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
if( ![result isKindOfClass:[NSString class]] )//error occured
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Inventory" message:#"unable to communicate with server" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
else
{
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
[self stopSpinner];
}
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if([ConfirmationAlert.title isEqualToString:#"Authentication"])
{
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
}
}
# pragma mark Parsing Delegate Methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"params"])
{
Obj_string = [[NSMutableString alloc]init];
LoginState =[[NSMutableString alloc]init];
hashkey=[[NSMutableString alloc]init];
validuser=[[NSMutableString alloc]init];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:#"name"])
{
self.LoginState=self.Obj_string;
}
else if([elementName isEqualToString:#"string"])
{
//NSLog(#"%#",Obj_string);
if([self.LoginState isEqualToString:#"hash_key"])
{
self.hashkey=self.Obj_string;
app.globalhash_key=self.hashkey;
}
if([self.LoginState isEqualToString:#"api"])
{
self.apikey=self.Obj_string;
app.globalApi_key=self.apikey;
}
if([self.LoginState isEqualToString:#"message"])
{
self.validuser=self.Obj_string;
}
}
[Obj_string release];
Obj_string = nil;
Obj_string = [[NSMutableString alloc]init];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[Obj_string appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
//[LoginState appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
-(NSString *)dateInFormat:(NSString*)stringFormat {
char buffer[80];
const char *format = [stringFormat UTF8String];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, format, timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}
- (NSString *)sha256:(NSString *)str
{
const char *inputString = [str UTF8String];
unsigned char hashedChars[32]; // 32bit encoding
//unsigned char hashedChars[64]; // 64 bit encoding
//unsigned char hashedChars[64]; //16 bit encoding
CC_SHA256(inputString , strlen(inputString), hashedChars);
NSData *hashedData = [NSData dataWithBytes:hashedChars length:32];//32bit encoding
//NSData *hashedData = [NSData dataWithBytes:hashedChars length:64]; //64bit encoding
//NSData *hashedData = [NSData dataWithBytes:hashedChars length:16]; //16bit encoding
NSLog(#"hashedData = %#", hashedData);
NSString *someString = [NSString stringWithFormat:#"%#", hashedData];
someString = [someString stringByReplacingOccurrencesOfString:#" " withString:#""];
someString = [someString stringByReplacingOccurrencesOfString:#"<" withString:#""];
someString = [someString stringByReplacingOccurrencesOfString:#">" withString:#""];
//return hash;
return someString;
}
- (NSString *)getMD5FromString:(NSString *)source
{
const char *src = [source UTF8String];
unsigned char result[16];
CC_MD5(src, strlen(src), result);
NSString *ret = [[[NSString alloc] initWithFormat:#"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] autorelease];
return [ret lowercaseString];
}
- (id)executeXMLRPCRequest:(XMLRPCRequest *)req
{
XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
return [userInfoResponse object];
}
-(void)ClickOnBack
{
[self dismissModalViewControllerAnimated:YES];
//[self.navigationController popViewControllerAnimated:YES];
//MainViewController *mainView=[[MainViewController alloc]init];
// [self.navigationController popToViewController:mainView animated:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
// Try to find next responder
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
// Found next responder, so set it.
[nextResponder becomeFirstResponder];
} else {
// Not found, so remove keyboard.
[textField resignFirstResponder];
}
return NO; // We do not want UITextField to insert line-breaks.
}
-(NSString*) digest:(NSString*)input
{
NSData *data = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// uint8_t digest[CC_SHA1_DIGEST_LENGTH];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA1(data.bytes, data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
// for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x", digest[i]];
return output;
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
The part in question is this
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
On the surface it seems really simple. The change I want to make is to remove this alert
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
However, any change to the alert causes the pushViewController to stop working. I have tried commenting the alert out,
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==TRUE)
{
// UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
//[LoginOK show];
//[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
I have tried rewriting the second if
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
if (app.Authorisation==FALSE)
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
I have also tried completely removing the second if
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
}
But the pushViewController will not work unless I have the alert in the code. I don't get any error, and the app does not crash, it just stays in the current page, so I am completely at a loss. It makes me think their is some action that is triggered by clicking "OK" in the alert, but I don't see anything in the code.
I have also stepped through the code to see if I can spot the problem but it seems fine.
In case it matters I am using xcode 4.2 and iOS 5 sdk.
Another strange occurance is that if I run the code like this
if ([self.validuser isEqualToString:#"Authenticated Successfully"])
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
}
else
{
UIAlertView *LoginError=[[UIAlertView alloc]initWithTitle:#"Authentication" message:self.validuser delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginError show];
[LoginError release];
}
and I get a login error (meaning it triggers the alert in the else). Then after clicking ok it moves on to the next page. I really don't understand how this could happen since they are in different part of the if. I must be missing something obvious.
The Uialertview delegate method never gets called, therefore never dismisses the modal view controller
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex
Just dismiss the view controller next to the commented code
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
I may be totally off base here, but did you try removing the entire block;
if (app.Authorisation==TRUE)
{ ***STARTING HERE
UIAlertView *LoginOK=[[UIAlertView alloc]initWithTitle:#"Authentication" message:#"Authenticated successfully!!!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[LoginOK show];
[LoginOK release];
}
else
{
MainViewController *main=[[MainViewController alloc]init];
[self.navigationController pushViewController:main animated:YES];
[main release];
} ***ENDING HERE
}
If you remove the alert then the delegate methods won't be called.
This part here:
- (void)alertView:(UIAlertView *)ConfirmationAlert didDismissWithButtonIndex:(NSInteger)buttonIndex {
if([ConfirmationAlert.title isEqualToString:#"Authentication"]) {
[self dismissModalViewControllerAnimated:YES];
app.Authorisation=FALSE;
}
}
Just put the code inside the if-block above into the block where you removed the alert.