xml post加载xml响应

时间:2012-01-24 17:53:56

标签: ios nsurlrequest nsmutableurlrequest

我试图点击REST api以查看用户是否有效。我知道connectionDidFinishLoading运行,但我不确定如何检查响应(xml)。请指教。

signIn功能让球滚动

- (IBAction)signIn:(id)sender;
{
    [emailError setHidden:YES];

    if([emailAddressTxt text] && [passwordTxt text]) {
        // send user/pass to server for validation
        if([self NSStringIsValidEmail:[emailAddressTxt text]]) {
            NSString *post = [NSString stringWithFormat:@"Email=%@&Password=%@", emailAddressTxt.text, passwordTxt.text];
            NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:[NSURL URLWithString:@"http://www.mySite.com/validate.php"]];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody:postData];
            [NSURLConnection connectionWithRequest:request delegate:self];
        }
    } else {
        // give error dialogue
        [emailError setText:@"User not found"];
        [emailError setHidden:NO];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //[signInData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    //[signInData appendData:d];
    // updated to:
    signInData = (NSMutableData *)d;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // Fail..
    [emailError setText:@"Connection Error"];
    [emailError setHidden:NO];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] initWithData:signInData encoding:NSUTF8StringEncoding];

    NSLog(@"%@", @"check");
    NSLog(@"%@", responseText);
}

// an example response would be:
// <string xmlns="http://thedomain.com/">invalid login</string>

1 个答案:

答案 0 :(得分:2)

通常要解析XML你会使用NSXMLParser,但是字符串响应很简单,如“<string xmlns="http://thedomain.com/">invalid login</string>”我假设有效登录看起来像这样:“{ {1}}“

如果是这种情况,您只需查找包含字符串<string xmlns="http://thedomain.com/">valid login</string>但不包含@"valid login"

的回复
@"invalid login"

如果(甚至更好)成功的回答是“if (([responseText rangeOfString:@"invalid login"].location == NSNotFound) && ([responseText rangeOfString:@"valid login"].location != NSNotFound)){ // Congrats valid } ”,则if语句变得更容易理解。

<string xmlns="http://thedomain.com/">successful login</string>