Iphone 当用户名/密码为´时如何显示操作表;Twitter不正确吗?

Iphone 当用户名/密码为´时如何显示操作表;Twitter不正确吗?,iphone,objective-c,xcode,twitter,Iphone,Objective C,Xcode,Twitter,当用户按下“推特”按钮,用户名或密码出错时,我希望我的应用程序显示一个操作表。 对于我的twitter函数,我使用Brandon Trebitowski提供的TwitterRequest.m/h。如果一切正常且用户名/密码正确,则我的应用程序中会出现这种情况: TwitterRequest * t = [[TwitterRequest alloc] init]; (...); [t statuses_update:twittermessage.te

当用户按下“推特”按钮,用户名或密码出错时,我希望我的应用程序显示一个操作表。 对于我的twitter函数,我使用Brandon Trebitowski提供的TwitterRequest.m/h。如果一切正常且用户名/密码正确,则我的应用程序中会出现这种情况:

        TwitterRequest * t = [[TwitterRequest alloc] init];
        (...);
        [t statuses_update:twittermessage.text delegate:self requestSelector:@selector(status_updateCallback:)];

        loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@"Posting to Twitter..." delegate:nil 
                                                cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        [loadingActionSheet showInView:self.view];
    }


    - (void) status_updateCallback: (NSData *) content {
        [loadingActionSheet dismissWithClickedButtonIndex:0 animated:YES];
        [loadingActionSheet release];
        NSLog(@"%@",[[NSString alloc] initWithData:content encoding:NSASCIIStringEncoding]);
    }
但是,当用户名/密码错误时,如何显示其他操作表? 这是TwitterRequest.m:

#import "TwitterRequest.h"

@implementation TwitterRequest

@synthesize username;
@synthesize password;
@synthesize receivedData;
@synthesize delegate;
@synthesize callback;
@synthesize errorCallback;

-(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector{
    isPost = NO;
    // Set the delegate and selector
    self.delegate = requestDelegate;
    self.callback = requestSelector;
    // The URL of the Twitter Request we intend to send
    NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/friends_timeline.xml"];
    [self request:url];
}

-(void)statuses_update:(NSString *)status delegate:(id)requestDelegate requestSelector:(SEL)requestSelector; {
    isPost = YES;
    // Set the delegate and selector
    self.delegate = requestDelegate;
    self.callback = requestSelector;
    // The URL of the Twitter Request we intend to send
    NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/update.xml"];
    requestBody = [NSString stringWithFormat:@"status=%@",status];
    [self request:url];
}

-(void)request:(NSURL *) url {
    theRequest   = [[NSMutableURLRequest alloc] initWithURL:url];

    if(isPost) {
        NSLog(@"ispost");
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [theRequest setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
        [theRequest setValue:[NSString stringWithFormat:@"%d",[requestBody length] ] forHTTPHeaderField:@"Content-Length"];
    }

    theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {
        // Create the NSMutableData that will hold
        // the received data
        // receivedData is declared as a method instance elsewhere
        receivedData=[[NSMutableData data] retain];
    } else {
        // inform the user that the download could not be made
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //NSLog(@"challenged %@",[challenge proposedCredential] );

    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:[self username]
                                                 password:[self password]
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];

    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that the user name and password
        // in the preferences are incorrect
        NSLog(@"Invalid Username or Password");
    }

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse

    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
    //[receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //NSLog([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];

    [theRequest release];

    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);

    if(errorCallback) {
        [delegate performSelector:errorCallback withObject:error];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data

    if(delegate && callback) {
        if([delegate respondsToSelector:self.callback]) {
            [delegate performSelector:self.callback withObject:receivedData];
        } else {
            NSLog(@"No response from delegate");
        }
    } 

    // release the connection, and the data object
    [theConnection release];
    [receivedData release];
    [theRequest release];
}

-(void) dealloc {
    [super dealloc];
}


@end

很抱歉提出这个愚蠢的问题,但我从一周前开始学习Objective-C和编程,我不知道如何正确地从ViewController与其他类交互。

要实现操作表,必须首先在头文件中实现UIActionSheetDelegate(将UIActionSheetDelegate包含在之间的@interface定义中)

在代码中,您将显示操作表并通过按下按钮捕捉操作。要显示操作表,请执行以下操作:

UIActionSheet *actionSheet = [[UIActionSheet alloc]
                              initWithTitle:@"Choose one, por favor"
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              destructiveButtonTitle:nil
                              otherButtonTitles:@"Save Favorite", @"Email", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.cancelButtonIndex = 2;
[actionSheet showInView:self.view];
[actionSheet release];
要对按钮按下进行操作,请使用以下方法:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // the user clicked one of the OK/Cancel buttons
    NSLog(@"The button index is: %i", buttonIndex);

    switch (buttonIndex) {
        case 0:
            NSLog(@"Button 0");
            [self saveNew];
            break;
        case 1:
            NSLog(@"Button 1");
            [self sendEmail];
            break;
        case 2:
            NSLog(@"Button 2");
            break;
        default:
            break;
    }
}
您的另一个选项是使用警报——对于不正确的用户名/密码,这可能是最佳选项。警报是显示在屏幕中央的模式框。要实现警报,请在头文件中实现UIAlertViewDelegate

警报代码示例如下所示:

UIAlertView *alert;
alert = [[UIAlertView alloc] initWithTitle:@"Ouch!"
  message:@"Your message is placed here"
  delegate:self 
  cancelButtonTitle:@"OK" 
  otherButtonTitles: nil];
[alert show];   
[alert release];

如果您希望在用户收到身份验证请求时做出反应,则需要在didReceiveAuthenticationChallenge中工作

具体来说,在这条线的正上方:

newCredential=[NSURLCredential credentialWithUser:[self username]
                                             password:[self password]
                                          persistence:NSURLCredentialPersistenceNone];
是您希望从用户处获取用户名和密码的位置

如果您想要处理身份验证失败,那么您需要借助于previousCountFailure if语句中的'else'子句

具体来说,在这一行之后,您要告诉用户他们失败了:

[[challenge sender] cancelAuthenticationChallenge:challenge];

谢谢,但它不起作用-我试图在TwitterRequst类中创建一个bool as属性,当到达重要的else子句时,它将被设置为FALSE。在我的另一个ViewController中,我创建了一个if(bool==FALSE){do something},但他总是将BOOL读为TRUE,即使BOOL将被设置为FALSE——我认为问题是,他读取if(BOOL==FALSE)-查询速度比另一个类快。我能做什么?为什么不在didReceiveAuthenticationChallenge函数中实际显示错误消息,而不是尝试使用标志和处理竞争条件(因为您使用的是网络信号,完成任何事情所需的时间并不是真正确定的)