1

我已经创建了一个登录视图。每次我登录它都会显示登录成功消息。即使我输入了错误的用户名和密码。我创建了静态登录页面。被提及的链接是示例 Web 服务链接。这是我现在正在使用的方法:请给我任何想法。在此先感谢。

loginPage.m

-

(IBAction)login:(id)sender

{

NSString *post = [NSString stringWithFormat:@"&Username=%@&Password=%@",@"username",@"password"];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];


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


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];


[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"HTTP://URL"]]];


[request setHTTPMethod:@"POST"];


[request setValue:postLength forHTTPHeaderField:@"Content-Length"];


[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];


[request setHTTPBody:postData];


NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];


if (conn)

{

NSLog(@"connection successful");

}

else

{


NSLog(@"Failed");


}

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

[textField resignFirstResponder];

return YES;

}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

[receivedData setLength:0];

// NSURL *theURL=[response URL];

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection

{

if(receivedData)

{

NSLog(@"success",[receivedData length]);

}

else

{

NSLog(@"Success",[receivedData length]);

}

}
4

5 回答 5

1
NSString *string= [NSString stringWithFormat:@"your Url.php?&Username=%@&Password=%@",username,password];
        NSLog(@"%@",string);
        NSURL *url = [NSURL URLWithString:string];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];

        NSURLResponse *response;
        NSError *err;
        NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
        NSLog(@"responseData: %@", responseData);
        NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"responseData: %@", str);
        NSString *str1 = @"1";
        if ([str isEqualToString:str1 ])
        {

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Successfully" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"" delegate:self cancelButtonTitle:@"Try Later" otherButtonTitles:@"Call", nil];
            alert.tag = 1;
            [alert show];
        }

不需要使用 JSON,你可以在没有 JSON 的情况下以一种简单的方式做到这一点!!!

于 2013-09-02T12:33:27.883 回答
0

试试下面的代码。

-(void)webservice_Call
{
NSString *urlString=@"http://api.openweathermap.org/data/2.1/find/city?lat=10.369&lon=122.5896";

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                   timeoutInterval:10];

[request setHTTPMethod: @"GET"];

NSError *requestError;
NSURLResponse *urlResponse = nil;


NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];

NSDictionary *resDictionary = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingMutableContainers error:Nil];

}
于 2014-10-29T12:25:18.597 回答
0
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];

    [alertView show];

}


- (IBAction)loginClicked:(id)sender {
    @try {

        if([[txtUserName text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) {
            [self alertStatus:@"Пожалуйста заполните все поля!!!" :@"Авторизация не удолась!"];
        } else {

            NSString *post =[[NSString alloc] initWithFormat:@"login=%@&pass=%@",[txtUserName text],[txtPassword text]];


            NSURL *url=[NSURL URLWithString:@"http:xxxxxxxx.xxx/?"];

            NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

            NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:url];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];

            NSError *error = [[NSError alloc] init];
            NSHTTPURLResponse *response = nil;
            NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];




            if ([response statusCode] >=200 && [response statusCode] <300)
            {
                NSData *responseData = [[NSData alloc]initWithData:urlData];
                NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];


                if([jsonObject objectForKey:@"error"])
                {
                    [self alertStatus:@"" :@""];

                } else {

                    [self alertStatus:@"" :@""];
                }

            } else {
                if (error) NSLog(@"Error: %@", error);
                [self alertStatus:@"Connection Failed" :@"Login Failed!"];
            }
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Login Failed." :@"Login Failed!"];
    }

    [txtUserName resignFirstResponder];
    [txtPassword resignFirstResponder];
}
于 2013-11-17T04:48:48.213 回答
0

iOS 9 版本的发布方法

    NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
                
    [post setValue:@“25” forKey:@"user_id"];

    NSArray* notifications = [NSArray arrayWithObjects:post, nil];
            
    NSError *writeError = nil;
           
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
            
    NSString *postLength = [NSString stringWithFormat:@"%d",[jsonData length]];
           
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
           
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://your/url]]];
          
    [request setHTTPMethod:@"POST"];
           
    [request setValue:postLength forHTTPHeaderField:@"Content-Length" ];
           
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
           
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
           
    [request setHTTPBody:jsonData];
                
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
     
    // Create a data task object to perform the data downloading.
            
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     
        data = [[NSData alloc]initWithData:urlData];

        NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }];
          
    [task resume];
于 2016-08-18T06:47:24.473 回答
0
-(void)apiCode
{
    NSString *string= [NSString stringWithFormat:@"http:url...project_id=1&user_id=58&question=%@&send_enquiry=%@",self.txtTitle.text,self.txtQuestion.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
    NSString *str1 = @"success";
    if ([str isEqualToString:str1 ])
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Successfully" message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Try Again" message:@"" delegate:self cancelButtonTitle:@"Try Later" otherButtonTitles:@"Call", nil];
        alert.tag = 1;
        [alert show];
    }
}
于 2017-01-11T06:06:47.293 回答