iOS 開發之 Web Service 調用

來源:互聯網
上載者:User

以下變更在 .h 檔案中聲明

NSMutableData *webData;
NSMutableString *soapReply;
NSURLConnection *conn;

NSXMLParser *xmlParser;
BOOL elementFound;

以下在 .m 中實現

//Validate User ID and Password by Web Service
- (void)loginValidate{

//[self loginValidate];
myIMEICode = @"03 600274 150967 3";
accessKey=@"NULL";

NSString *tstIMEI = myIMEICode;
NSString *userString = @"NULL";

if ([userID.text isEqualToString:@"iosappsvisitor"]) {
userString = @"domain\\general";
}
else {
userString = userID.text;
}

NSArray *userArray = [userString componentsSeparatedByString:@"\\" ];
NSString *userIDOnly = [userArray objectAtIndex:1];
NSString *userDomain = [userArray objectAtIndex:0];

NSString *newPassword=[[NSString alloc] init];

newPassword=[self encryptPassword];
NSLog(newPassword);
NSString *soapMsg = [NSString stringWithFormat:
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>" 
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<zApps_Ins_Login_Tx xmlns=\"http://cbi.crystalgroup.com.hk/\">"
"<p_sUserID>%@</p_sUserID>"
"<p_sUserPassword>%@</p_sUserPassword>"
"<p_sIMEICode>%@</p_sIMEICode>"
"<p_sDomain>%@</p_sDomain>"
"</zApps_Ins_Login_Tx>"
"</soap:Body>"
"</soap:Envelope>", userIDOnly, newPassword, tstIMEI,userDomain];

NSString *wsURL = [[NSString alloc] init]; 
wsURL=@"http://tst.tst.com/wsAppsiDevice/Service.asmx";//Testing URL

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:wsURL]];
[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"http://cbi.crystalgroup.com.hk/zApps_Ins_Login_Tx" forHTTPHeaderField:@"SOAPAction"];
[req addValue:[NSString stringWithFormat:@"%d", [soapMsg length]] forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn=[[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}

}

-(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 {

//NSString *msgResult = [error description];
[webData release];
[connection release];

}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {

return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];

}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
if (xmlParser) {
[xmlParser release];
}
xmlParser=[[NSXMLParser alloc] initWithData:webData];
[xmlParser setDelegate: self];

[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];

if ([accessKey isEqualToString:@"NULL"])
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Warning" 
 message:@"Invalid User ID / Password, please try again!" 
delegate:nil cancelButtonTitle:@"OK" 
otherButtonTitles:nil];
[alert show];
[alert release];
}
else {

// Write data to plist
// BEGIN
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/data.plist"];

//
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *plistDict;
if ([fileManager fileExistsAtPath: filePath])
{
plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
}else{
plistDict = [[NSMutableDictionary alloc] init];
}

NSString *userString = @"NULL";

if ([userID.text isEqualToString:@"iosappsvisitor"]) {
userString = @"hk\\general";
}
else {
userString = userID.text;
}

NSArray *userArray = [userString componentsSeparatedByString:@"\\" ];
NSString *userIDOnly = [userArray objectAtIndex:1];

[plistDict setValue:userIDOnly forKey:@"UserID"];
[plistDict setValue:userPassword.text forKey:@"UserPwd"];
[plistDict setValue:accessKey forKey:@"UserAccessKey"];
[plistDict setValue:myIMEICode forKey:@"UserIMEI"];

if ([plistDict writeToFile:filePath atomically: YES]) {
NSLog(@"writePlist success");
} else {
NSLog(@"writePlist fail");
}

[plistDict release];
// END

}


[connection release];
[webData release];
}

-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI
 qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
//if ([elementName isEqualToString:@"GetQuoteResult"]){
//if ([elementName isEqualToString:@"zIns_Login_TxResult"]) {
if ([elementName isEqualToString:@"zApps_Ins_Login_TxResult"]) {
if (!soapReply){
soapReply=[[NSMutableString alloc] init];
}
elementFound=YES;
}
}

-(void) parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
if (elementFound) {
[soapReply appendString:string];
}
}

-(void) parser: (NSXMLParser *) parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName {
//if ([elementName isEqualToString:@"GetQuoteResult"]){
//if ([elementName isEqualToString:@"zIns_Login_TxResult"]) {
if ([elementName isEqualToString:@"zApps_Ins_Login_TxResult"]) {

//if (!soapReply) {
// soapReply = [[NSMutableString alloc] init];
//}

NSString *accessKey1 = [soapReply description];
//[soapReply setString:@""];
elementFound=NO;

accessKey = accessKey1;

if ([accessKey1 isEqualToString:@"NULL"]) {
accessKey = @"NULL";
}
else if (accessKey1!=nil)
{
/*
UIAlertView *alertOK=[[UIAlertView alloc] initWithTitle:@"Validate" 
message: accessKey1 
delegate:nil cancelButtonTitle:@"OK" 
otherButtonTitles:nil];
[alertOK show];
[alertOK release];
*/

iPad_Demo2AppDelegate *appDelegate =(iPad_Demo2AppDelegate *)[[UIApplication sharedApplication] delegate];
[self.view removeFromSuperview];

//[self.navigationController popToRootViewControllerAnimated:YES];

appDelegate.myKey=accessKey;
//[appDelegate.window addSubview:appDelegate.topNewsViewController.view];
//splitViewController
[appDelegate.window addSubview:appDelegate.splitViewController.view];

}
else {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Validate" 
 message:@"Invalid user id or password, please try again." 
delegate:nil cancelButtonTitle:@"OK" 
otherButtonTitles:nil];
[alert show];
[alert release];
}

//[soapReply setString:@""];
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.