简体   繁体   English

将Obj-c的php的POST变量不起作用

[英]POST variables to php from Obj-c its doesnt work

Hello Im newbie with iOS and Xcode, but I have to do a login screen,and that login screen don't response me anything after try connect the php on server. 您好,我是iOS和Xcode的新手,但是我必须做一个登录屏幕,尝试连接服务器上的php后,该登录屏幕没有任何响应。

- (IBAction)btnLogin:(id)sender {


    NSInteger success = 0;
    @try {

        if([[self.insUsuario text] isEqualToString:@""] || [[self.insSenha text] isEqualToString:@""] ) {

            [self alertStatus:@"Insira o email e a senha!" :@"Erro" :0];

        } else {
            //ViewPontos *WP = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewPontos"];
            //WP.gUser = self.insUsuario.text;

            NSString *post =[[NSString alloc] initWithFormat:@"usuario=%@&senha=%@",[self.insUsuario text],[self.insSenha text]];

            NSLog(@"PostData: %@",post);

            NSURL *url=[NSURL URLWithString:@"http://emporio56/apiapp/pegarPontos.php"];

            //NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSLog(@"DATA %@", postData);

            NSString *postLength = [NSString stringWithFormat:@"%d", [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 setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:postData];
            [request setHTTPShouldHandleCookies:YES];

            NSLog(@"%@", request);

            NSURLConnection *conn= [[NSURLConnection alloc]initWithRequest:request delegate:self];
            if(conn)
            {

                NSError *error = [[NSError alloc] init];
                NSHTTPURLResponse *response = nil;
                NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                NSLog(@"Response code: %ld", (long)[response statusCode]);

                if ([response statusCode] >= 200 && [response statusCode] < 300)
                {
                    //NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                   NSLog(@"Response ==> %@", response);

                    NSError *error = nil;
                    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers error:&error];
                    success = [jsonData[@"success"] integerValue];
                    NSLog(@"Success: %ld",(long)success);

                    if(success == 1)
                    {
                        NSLog(@"Login SUCCESS");
                    } else {

                        NSString *error_msg = (NSString *) jsonData[@"error_message"];
                        [self alertStatus:error_msg :@"Erro" :0];
                    }

                } else {
                    //if (error) NSLog(@"Error: %@", error);
                    [self alertStatus:@"Erro!" :@"Sign in Failed!" :0];
                }


                NSLog(@"Conectado");
            }
            else
            {
                NSLog(@"Nao conectou");
            }
            //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
        }
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        [self alertStatus:@"Sign in Failed." :@"Erro" :0];
    }
    if (success) {
        [self performSegueWithIdentifier:@"login_success" sender:self];
    }
}

    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        // A response has been received, this is where we initialize the instance var you created
        // so that we can append data to it in the didReceiveData method
        // Furthermore, this method is called each time there is a redirect so reinitializing it
        // also serves to clear it
        _responseData = [[NSMutableData alloc] init];
    }

    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        // Append the new data to the instance variable you declared
        [_responseData appendData:data];
    }

    - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                      willCacheResponse:(NSCachedURLResponse*)cachedResponse {
        // Return nil to indicate not necessary to store a cached response for this connection
        return nil;
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        // The request is complete and data has been received
        // You can parse the stuff in your instance variable now

    }

    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        // The request has failed for some reason!
        // Check the error var
    }

after run the code to test and put the username and password, I don't get response from the server its always response = (null) , someone knows what can I do to fix it? 在运行代码以测试并输入用户名和密码之后,我没有从服务器获得响应,始终response = (null) ,有人知道该如何解决? because Ive tried the most of codes that can you find in the web and it didn't work as well how the people say, I using the same php to connect an android application but it works, so what Im doing wrong on my code to POST the username and password on the php file and connect to the db. 因为我已经尝试了大部分可以在网络上找到的代码,但是人们说的却不尽人意,我使用相同的php连接android应用程序,但是它可以正常工作,所以我在我的代码上做错了什么将用户名和密码发布到php文件中,并连接到数据库。

Sorry for the problem, but I don't know what is happened 对不起,这个问题,但是我不知道发生了什么

Please try this. 请尝试这个。 Hope it will solve your problem. 希望它能解决您的问题。

NSString *stringUrl = [NSString stringWithFormat:@"http://emporio56/apiapp/pegarPontos.php?usuario=%@&senha=%@",[self.insUsuario text],[self.insSenha text]];
    NSURL *url = [NSURL URLWithString:stringUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary *dicYourResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
             NSLog(@"%@",dicYourResponse);
         }
     }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM