iphone twitter posting

Posted by user313100 on Stack Overflow See other posts from Stack Overflow or by user313100
Published on 2010-05-02T19:22:29Z Indexed on 2010/05/02 19:28 UTC
Read the original article Hit count: 687

Filed under:
|
|

I have some twitter code I modified from: http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/

His code used view alerts to login and post to twitter but I wanted to change mine to use windows. It is mostly working and I can login and post to Twitter. However, when I try to post a second time, the program crashes with a: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFString text]: unrecognized selector sent to instance 0xc2d560'

I'm a bit of a coding newbie so any help would be appreciated. If I need to post more code, ask.

#import "TwitterController.h"
#import "xmacros.h"

#define XAGENTS_TWITTER_CONFIG_FILE DOC_PATH(@"xagents_twitter_conifg_file.plist")

static TwitterController* agent;

@implementation TwitterController

BOOL isLoggedIn;

@synthesize parentsv, sharedLink;


-(id)init
{
self = [super init];

maxCharLength = 140;
parentsv = nil;

isLogged = NO;
isLoggedIn = NO;

txtMessage = [[UITextView alloc] initWithFrame:CGRectMake(30, 225, 250, 60)];
UIImageView* bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fb_message_bg.png"]];
bg.frame = txtMessage.frame;

lblCharLeft = [[UILabel alloc] initWithFrame:CGRectMake(15, 142, 250, 20)]; 
lblCharLeft.font = [UIFont systemFontOfSize:10.0f]; 
lblCharLeft.textAlignment = UITextAlignmentRight;
lblCharLeft.textColor = [UIColor whiteColor]; 
lblCharLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; 

txtUsername = [[UITextField alloc]initWithFrame:CGRectMake(125, 190, 150, 30)]; 
txtPassword = [[UITextField alloc]initWithFrame:CGRectMake(125, 225, 150, 30)]; 
txtPassword.secureTextEntry = YES; 

lblId = [[UILabel alloc]initWithFrame:CGRectMake(15, 190, 100, 30)]; 
lblPassword = [[UILabel alloc]initWithFrame:CGRectMake(15, 225, 100, 30)];
lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(80, 170, 190, 30)];
lblId.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; 
lblPassword.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
lblTitle.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; 
lblId.textColor = [UIColor whiteColor]; 
lblPassword.textColor = [UIColor whiteColor]; 
lblTitle.textColor = [UIColor whiteColor];  

txtMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0]; 

lblId.text = @"Username:"; 
lblPassword.text =@"Password:";
lblTitle.text = @"Tweet This Message";
lblId.textAlignment = UITextAlignmentRight; 
lblPassword.textAlignment = UITextAlignmentRight; 
lblTitle.textAlignment = UITextAlignmentCenter;

txtUsername.borderStyle = UITextBorderStyleRoundedRect; 
txtPassword.borderStyle = UITextBorderStyleRoundedRect; 

txtMessage.delegate = self; 
txtUsername.delegate = self; 
txtPassword.delegate = self; 

login = [[UIButton alloc] init];
login = [UIButton buttonWithType:UIButtonTypeRoundedRect];
login.frame = CGRectMake(165, 300, 100, 30);
[login setTitle:@"Login" forState:UIControlStateNormal];
[login addTarget:self action:@selector(onLogin) forControlEvents:UIControlEventTouchUpInside];

cancel = [[UIButton alloc] init];
cancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
cancel.frame = CGRectMake(45, 300, 100, 30);
[cancel setTitle:@"Back" forState:UIControlStateNormal];
[cancel addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside];

post = [[UIButton alloc] init];
post = [UIButton buttonWithType:UIButtonTypeRoundedRect];
post.frame = CGRectMake(165, 300, 100, 30);
[post setTitle:@"Post" forState:UIControlStateNormal];
[post addTarget:self action:@selector(onPost) forControlEvents:UIControlEventTouchUpInside];

back = [[UIButton alloc] init];
back = [UIButton buttonWithType:UIButtonTypeRoundedRect];
back.frame = CGRectMake(45, 300, 100, 30);
[back setTitle:@"Back" forState:UIControlStateNormal];
[back addTarget:self action:@selector(onCancel) forControlEvents:UIControlEventTouchUpInside];


loading1 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
loading1.frame = CGRectMake(140, 375, 40, 40);
loading1.hidesWhenStopped = YES;
[loading1 stopAnimating];

loading2 = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
loading2.frame = CGRectMake(140, 375, 40, 40);
loading2.hidesWhenStopped = YES;
[loading2 stopAnimating];

twitterWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 

[twitterWindow addSubview:txtUsername];
[twitterWindow addSubview:txtPassword];
[twitterWindow addSubview:lblId];
[twitterWindow addSubview:lblPassword];
[twitterWindow addSubview:login];
[twitterWindow addSubview:cancel];
[twitterWindow addSubview:loading1];

UIImageView* logo = [[UIImageView alloc] initWithFrame:CGRectMake(35, 165, 48, 48)];
logo.image = [UIImage imageNamed:@"Twitter_logo.png"];
[twitterWindow addSubview:logo];

[logo release];

twitterWindow2 = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

[twitterWindow2 addSubview:lblTitle];
[twitterWindow2 addSubview:lblCharLeft];
[twitterWindow2 addSubview:bg];
[twitterWindow2 addSubview:txtMessage];
[twitterWindow2 addSubview:lblURL];
[twitterWindow2 addSubview:post];
[twitterWindow2 addSubview:back];
[twitterWindow2 addSubview:loading2];
[twitterWindow2 bringSubviewToFront:txtMessage];

UIImageView* logo1 = [[UIImageView alloc] initWithFrame:CGRectMake(35, 155, 42, 42)];
logo1.image = [UIImage imageNamed:@"twitter-logo-twit.png"];
[twitterWindow2 addSubview:logo1];

[logo1 release];

twitterWindow.hidden = YES;
twitterWindow2.hidden = YES;

return self;
}

-(void) onStart
{
[[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationPortrait];
twitterWindow.hidden = NO;
[twitterWindow makeKeyWindow];

[self refresh];

if(isLogged)
{
    twitterWindow.hidden = YES;
    twitterWindow2.hidden = NO;
    [twitterWindow2 makeKeyWindow];
}
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[textField becomeFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return NO;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
const char* str = [text UTF8String];

int s = str[0];
if(s!=0)
    if((range.location + range.length) > maxCharLength){
        return NO;
    }else{
        int left = 139 - ([sharedLink length] + [textView.text length]);
        lblCharLeft.text= [NSString stringWithFormat:@"%d",left];


        // this fix was done by Jackie
        //http://amanpages.com/sample-iphone-example-project/twitteragent-tutorial-tweet-from-iphone-app-in-one-line-code-with-auto-tinyurl/#comment-38026299
        if([text isEqualToString:@"\n"]){
            [textView resignFirstResponder];
            return FALSE;
        }else{
            return YES;
        }
    }

int left = 139 - ([sharedLink length] + [textView.text length]);
lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
return YES;
}

-(void) onLogin
{
[loading1 startAnimating];

NSString *postURL = @"http://twitter.com/statuses/update.xml";
NSString *myRequestString = [NSString stringWithFormat:@""];

NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ];
[ request setHTTPMethod: @"POST" ];
[ request setHTTPBody: myRequestData ];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (!theConnection) {
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];
}      
[request release];
}

-(void) onCancel
{
[[NSUserDefaults standardUserDefaults] setValue:@"NotActive" forKey:@"Twitter"];
twitterWindow.hidden = YES;
[[UIApplication sharedApplication]setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
}

-(void) onPost 
{
[loading2 startAnimating];

NSString *postURL = @"http://twitter.com/statuses/update.xml";
NSString *myRequestString;
if(sharedLink){
    myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@\n%@",txtMessage.text,sharedLink]];
}else{
    myRequestString = [NSString stringWithFormat:@"&status=%@",[NSString stringWithFormat:@"%@",txtMessage.text]];
}

NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:postURL ] ];
[ request setHTTPMethod: @"POST" ];
[ request setHTTPBody: myRequestData ];

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (!theConnection) {
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Failed to Connect to twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];

}      
[request release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
if(isAuthFailed){
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Login Failed" message:@"Invalid ID/Password" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];
}else{
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Connection Failed" message:@"Failed to connect to Twitter" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];

}

isAuthFailed = NO;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
isAuthFailed = NO;

[loading1 stopAnimating];
[loading2 stopAnimating];

if(isLogged)
{
    UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
    [aler show];
    [aler release];

    txtMessage = @"";
    [self refresh];
}

else
{
    twitterWindow.hidden = YES;
    twitterWindow2.hidden = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"notifyTwitterLoggedIn" object:nil userInfo:nil];
}

isLogged = YES;
isLoggedIn = YES;
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSDictionary* config = [NSDictionary dictionaryWithObjectsAndKeys:txtUsername.text,@"username",txtPassword.text,@"password",nil];
[config writeToFile:XAGENTS_TWITTER_CONFIG_FILE atomically:YES];
if ([challenge previousFailureCount] == 0) {
    NSURLCredential *newCredential;
    newCredential=[NSURLCredential credentialWithUser:txtUsername.text
                                             password:txtPassword.text
                                          persistence:NSURLCredentialPersistenceNone];
    [[challenge sender] useCredential:newCredential
           forAuthenticationChallenge:challenge];
} else {
    isAuthFailed = YES;
    [[challenge sender] cancelAuthenticationChallenge:challenge];
}
}

-(void) refresh
{
NSDictionary* config = [NSDictionary dictionaryWithContentsOfFile:XAGENTS_TWITTER_CONFIG_FILE];
if(config){
    NSString* uname = [config valueForKey:@"username"];
    if(uname){
        txtUsername.text = uname;
    }

    NSString* pw = [config valueForKey:@"password"];
    if(pw){
        txtPassword.text = pw;
    }

}
}

+ (TwitterController*)defaultAgent{
if(!agent){
    agent = [TwitterController new];
}
return agent;
}       

-(void)dealloc 
{
[super dealloc];

[txtMessage release];
[txtUsername release];
[txtPassword release];

[lblId release];
[lblPassword release];
[lblURL release];

[twitterWindow2 release];
[twitterWindow release];
}


@end

© Stack Overflow or respective owner

Related posts about xcode

Related posts about iphone