2013-12-16 79 views
0

我的任務是通過解析xml數據來做登錄表單,也就是通過url發送用戶名和密碼,並且必須解析xml,我成功解析了來自url的xml數據,現在的問題是我無法從解析的XML讀取狀態數據。 for循環未執行。請幫助我如何做到這一點。 這裏是我的代碼Objective-C:For循環未執行?

#import "RTVersion1ViewController.h" 

@interface RTVersion1ViewController() 

@end 

@implementation RTVersion1ViewController 
@synthesize user,pass,username,pass1,webData,stat,sessid; 
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict 
{ 
    if([elementName isEqualToString:@"root"]) { 
     //Initialize the array. 
     rssOutputData = [[NSMutableArray alloc] init]; 
    } 
    else if([elementName isEqualToString:@"userDetails"]) { 
     //Initialize the book. 
     aLogin = [[Login alloc] init]; 
     //Extract the attribute here. 
     aLogin.userId = [[attributeDict objectForKey:@"userId"] integerValue]; 
     NSLog(@"Reading id value :%d", aLogin.userId); 
    } 
    NSLog(@"Processing Element: %@", elementName); 
} 
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 
    if(!nodecontent) 
     nodecontent = [[NSMutableString alloc] initWithString:string];else 
      [nodecontent appendString:string]; 
    NSLog(@"Processing Value: %@", nodecontent); 
} 
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
    namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { 
    if([elementName isEqualToString:@"root"]) 
     return; 
    if([elementName isEqualToString:@"userDetails"]) { 
     [rssOutputData addObject:aLogin]; 
     [aLogin release]; 
     aLogin= nil; 
    } 
    else 
     [aLogin setValue:nodecontent forKey:elementName]; 
    [nodecontent release]; 
    nodecontent = nil; 
} 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] 
            initWithTarget:self 
            action:@selector(dismissKeyboard)]; 

    [self.view addGestureRecognizer:tap]; 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    NSString *firstName = [defaults objectForKey:@"firstname"]; 
    NSString *lastName = [defaults objectForKey:@"lastname"]; 
    user.text = firstName; 
    pass.text = lastName; 
    // Do any additional setup after loading the view, typically from a nib. 
} 
-(void)viewDidAppear:(BOOL)animated { 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    // check if user is alraidy Login 
    if([defaults objectForKey:@"firstname"]!=nil && [defaults objectForKey:@"lastname"]!=nil){ 
    [self performSegueWithIdentifier:@"login" sender:defaults]; 
    } 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
-(void)dismissKeyboard { 
    [user resignFirstResponder]; 
    [pass resignFirstResponder]; 
} 

- (void)dealloc { 
    [user release]; 
    [pass release]; 
    [super dealloc]; 
} 
- (void) alertStatus:(NSString *)msg :(NSString *)title 
{ 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title 
                 message:msg 
                 delegate:self 
               cancelButtonTitle:@"Ok" 
               otherButtonTitles:nil, nil];  
    [alertView show]; 
} 
- (IBAction)Submit:(id)sender { 
    username =user.text; 
    pass1 = pass.text; 
    if([user.text isEqualToString:@"" ]|| [pass.text isEqualToString:@""]) 
    { 
     [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"]; 
     //greeting.text = @"Input Your Value"; 
     [user resignFirstResponder]; 
     [pass resignFirstResponder]; 
     return; 
    } 
    NSLog(@"%@%@",username,pass1); 
    NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",username,pass1]; 
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 
    //NSURL *url = [NSURL URLWithString:@"http://192.168.1.164:8080/RestoreTogether/userProfile/verifyUserDetail1"]; 
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; 
    // [theRequest addRequestHeader:@"Content-Type" value:@"application/xml"]; 
    [theRequest setHTTPMethod:@"POST"]; 
    [theRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"]; 
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [theRequest setHTTPBody:postData]; 
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
    if(theConnection) 
    { 
     webData = [[NSMutableData data] retain]; 
     NSLog(@"%@",webData); 
    } 
    } 
-(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 
{ 
    [webData release]; 
    [connection release]; 
} 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    samplearray = [[NSMutableArray alloc]init]; 
    xmlParserObject = [[NSXMLParser alloc] initWithData:webData]; 
    [xmlParserObject setDelegate:self]; 
    [xmlParserObject parse]; 
    for (int i =0; i<[rssOutputData count]; i++) { 
     Login *log = [rssOutputData objectAtIndex:i]; 
     sessid = log.userId; 
     NSLog(@"%d",sessid); 
     stat = log.status; 
     NSLog(@"%@",stat); 
     [samplearray addObject:log]; 
    } 

    [connection release]; 

} 

@end 

這裏是一個沒有工作

-(void)connectionDidFinishLoading:(NSURLConnection *)connection { 
     samplearray = [[NSMutableArray alloc]init]; 
     xmlParserObject = [[NSXMLParser alloc] initWithData:webData]; 
     [xmlParserObject setDelegate:self]; 
     [xmlParserObject parse]; 
     for (int i =0; i<[rssOutputData count]; i++) { 
      Login *log = [rssOutputData objectAtIndex:i]; 
      sessid = log.userId; 
      NSLog(@"%d",sessid); 
      stat = log.status; 
      NSLog(@"%@",stat); 
      [samplearray addObject:log]; 
     } 

     [connection release]; 

    } 

這裏的循環是控制檯輸出(已解析的XML輸出):

2013-12-16 18:37:21.498 RTVersion1[3238:c07] [email protected] 
2013-12-16 18:37:21.501 RTVersion1[3238:c07] <> 
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: root 
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: userDetail 
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Element: userId 
2013-12-16 18:37:21.604 RTVersion1[3238:c07] Processing Value: 20 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userFirstName 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: u1 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userLastName 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: u 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userUserType 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Value: INDIVIDUAL 
2013-12-16 18:37:21.605 RTVersion1[3238:c07] Processing Element: userUserName 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: [email protected] 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: status 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: true 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: sessionvalue 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Value: 1_MX40NDQ1OTU2Mn5-VGh1IERlYyAwNSAwMjo0NjozNCBQU1QgMjAxM34wLjc1MTEzNTV- 
2013-12-16 18:37:21.606 RTVersion1[3238:c07] Processing Element: tokenvalue 
2013-12-16 18:37:21.607 RTVersion1[3238:c07] Processing Value: T1==cGFydG5lcl9pZD00NDQ1OTU2MiZzZGtfdmVyc2lvbj10YnJ1YnktdGJyYi12MC45MS4yMDExLTAyLTE3JnNpZz1jYjhhMjZmODQxNGUyNWM4Yzc3OWU4YzE3MTQ5ZmI4ZmYyOWFiMDE2OnJvbGU9cHVibGlzaGVyJnNlc3Npb25faWQ9MV9NWDQwTkRRMU9UVTJNbjUtVkdoMUlFUmxZeUF3TlNBd01qbzBOam96TkNCUVUxUWdNakF4TTM0d0xqYzFNVEV6TlRWLSZjcmVhdGVfdGltZT0xMzg2MjQwNDM1Jm5vbmNlPTAuNTgzNzUzMzA4MzA2MTc3OSZleHBpcmVfdGltZT0xMzg4ODMyMjY5JmNvbm5lY3Rpb25fZGF0YT0= 

請幫助我的朋友在此先感謝

+1

rssOutputData.count小於1. –

+0

打印您的[rssOutputData count]以檢查它 – Vame

+0

它顯示值爲0 – Naresh

回答

1

因爲[rssOutputData count]在啓動時爲零,解析成功後會得到數據。

你正在把你的循環放在[xmlParserObject parse]之後。

[xmlParserObject parse]; 
     for (int i =0; i<[rssOutputData count]; i++) { 

從解析器獲取完整結果後進行循環。 所以把你的循環內didEndElement

if([elementName isEqualToString:@"root"]) 
//Your for loop should be here, 
     return; 
+0

s我只做了。我只在解析器之後放置了循環,並且我在didStartElement – Naresh

+0

nop中聲明瞭我的數組,但它沒有問題,只是在[xmlParserObject解析]之後放置了for循環,但解析尚未啓動。 – Rajneesh071

+0

它顯示ID值爲0和狀態值爲空 – Naresh

3

移動rssOutputData = [[NSMutableArray alloc] init];viewDidLoad或模型/類的init

您在委託中多次使用和分配,這是不正確的。

-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict 
{ 
    if([elementName isEqualToString:@"root"]) { 
     //Initialize the array. 
     rssOutputData = [[NSMutableArray alloc] init]; 
+0

我移動仍發生同樣的問題 – Naresh

0

在你的XML中有「userDetail」標籤,你在你的解析器中找到「userDetails」:didStartElement:方法。我認爲這是你的問題的原因,刪除額外的「s」,你會得到登錄項目。