Advertisement
Guest User

Ios WEb Service Communication

a guest
Dec 17th, 2013
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.    
  2.  
  3.     I am calling this web-service for test purpose and it is working fine.
  4.     <?php
  5.        
  6.     header('Content-type: application/json');
  7.     if($_POST) {
  8.         if($_POST['email'] == 'saad.bsit@hotmail.com' && $_POST['password'] == '12345') {
  9.         echo '{"success":1}';
  10.      } else {
  11.         echo '{"success":0,"error_message":"Username and/or password is invalid."}';
  12.     }
  13.     }else {    echo '{"success":0,"error_message":"Username and/or password is invalid."}';}
  14.     ?>
  15.      
  16.     action on button in sign in page
  17.     - (IBAction)btnSignIn:(id)sender {
  18.       @try {
  19.            
  20.             if([[txtUserEmail text] isEqualToString:@""] || [[txtUserPassword text] isEqualToString:@""] ) {
  21.                 [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
  22.             } else {
  23.                 NSString *post =[[NSString alloc] initWithFormat:@"email=%@&password=%@",[txtUserEmail text],[txtUserPassword text]];
  24.                 NSLog(@"PostData: %@",post);
  25.                
  26.                 NSURL *url=[NSURL URLWithString:@"http://localhost/colorSearch/sample_code.php"];
  27.                
  28.                 NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  29.                
  30.                 NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
  31.                
  32.                 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  33.                 [request setURL:url];
  34.                 [request setHTTPMethod:@"POST"];
  35.                 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  36.                 [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
  37.                 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  38.                 [request setHTTPBody:postData];
  39.                
  40.                 //[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
  41.                
  42.                 NSError *error = [[NSError alloc] init];
  43.                 NSHTTPURLResponse *response = nil;
  44.                 NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  45.                
  46.                 NSLog(@"Response code: %d", [response statusCode]);
  47.                 if ([response statusCode] >=200 && [response statusCode] <300)
  48.                 {
  49.                     NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  50.                     NSLog(@"Response ==> %@", responseData);
  51.                    
  52.                     SBJsonParser *jsonParser = [SBJsonParser new];
  53.                     NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
  54.                     NSLog(@"%@",jsonData);
  55.                     NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];
  56.                     NSLog(@"%d",success);
  57.                     if(success == 1)
  58.                     {
  59.                         NSLog(@"Login SUCCESS");
  60.                         [self alertStatus:@"Logged in Successfully." :@"Login Success!"];
  61.                                ColorPickerViewController *cpvc =[[ColorPickerViewController alloc] init];
  62.                                [self.navigationController pushViewController:cpvc animated:YES];
  63.                        
  64.                     } else {
  65.                        
  66.                         NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
  67.                         [self alertStatus:error_msg :@"Login Failed!"];
  68.                     }
  69.                    
  70.                 } else {
  71.                     if (error) NSLog(@"Error: %@", error);
  72.                     [self alertStatus:@"Connection Failed" :@"Login Failed!"];
  73.                 }
  74.             }
  75.         }
  76.         @catch (NSException * e) {
  77.             NSLog(@"Exception: %@", e);
  78.             [self alertStatus:@"Login Failed." :@"Login Failed!"];
  79.         }
  80.      
  81.      
  82.      
  83.      
  84.     }
  85.     - (void) alertStatus:(NSString *)msg :(NSString *)title
  86.     {
  87.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
  88.                                                             message:msg
  89.                                                            delegate:self
  90.                                                   cancelButtonTitle:@"Ok"
  91.                                                   otherButtonTitles:nil, nil];
  92.        
  93.         [alertView show];
  94.     }
  95.      
  96.     But if I try this which is the actual one code the code didn't execute. I think web service is not getting proper UrlRequest. This web service is working on tags, which I think is missing in my Request, My friend is using the same in Android and it is working fine for him, So in IOS how can we use this.
  97. In very beginning few lines you will get my point so I think there is no need to look all below code.
  98.    
  99.    Actual Web-service.
  100.    
  101.    
  102.    <?php
  103.    
  104.    /**
  105.    PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
  106.    **/
  107.    
  108.    if (isset($_POST['tag']) && $_POST['tag'] != '') {
  109.       // Get tag
  110.       $tag = $_POST['tag'];
  111.    
  112.       // Include Database handler
  113.       require_once 'include/DB_Functions.php';
  114.       $db = new DB_Functions();
  115.       // response Array
  116.       $response = array("tag" => $tag, "success" => 0, "error" => 0);
  117.    
  118.       // check for tag type
  119.       if ($tag == 'login') {
  120.           // Request type is check Login
  121.           $email = $_POST['email'];
  122.           $password = $_POST['password'];
  123.    
  124.           // check for user
  125.           $user = $db->getUserByEmailAndPassword($email, $password);
  126.           if ($user != false) {
  127.               // user found
  128.                
  129.               // echo json with success = 1
  130.               $response["success"] = 1;
  131.               $response["user"]["fname"] = $user["firstname"];
  132.               $response["user"]["lname"] = $user["lastname"];
  133.               $response["user"]["email"] = $user["email"];
  134.       $response["user"]["uname"] = $user["username"];
  135.               $response["user"]["uid"] = $user["unique_id"];
  136.               $response["user"]["created_at"] = $user["created_at"];
  137.              
  138.               echo json_encode($response);
  139.           } else {
  140.               // user not found
  141.               // echo json with error = 1
  142.               $response["error"] = 1;
  143.               $response["error_msg"] = "Incorrect email or password!";
  144.               echo json_encode($response);
  145.              
  146.           }
  147.       }
  148.     else if ($tag == 'chgpass'){
  149.     $email = $_POST['email'];
  150.    
  151.     $newpassword = $_POST['newpas'];
  152.    
  153.    
  154.     $hash = $db->hashSSHA($newpassword);
  155.           $encrypted_password = $hash["encrypted"]; // encrypted password
  156.           $salt = $hash["salt"];
  157.     $subject = "Change Password Notification";
  158.            $message = "Hello User,\n\nYour Password is sucessfully changed.\n\nRegards,\nDigitalnet Team.";
  159.             $from = "contact@Digitalnet.com";
  160.             $headers = "From:" . $from;
  161.    if ($db->isUserExisted($email)) {
  162.    
  163.    $user = $db->forgotPassword($email, $encrypted_password, $salt);
  164.    if ($user) {
  165.            $response["success"] = 1;
  166.             mail($email,$subject,$message,$headers);
  167.            echo json_encode($response);
  168.    }
  169.    else {
  170.    $response["error"] = 1;
  171.    echo json_encode($response);
  172.    }
  173.    
  174.    
  175.               // user is already existed - error response
  176.            
  177.            
  178.           }
  179.              else {
  180.    
  181.               $response["error"] = 2;
  182.               $response["error_msg"] = "User not exist";
  183.                echo json_encode($response);
  184.    
  185.    }
  186.    }
  187.    else if ($tag == 'forpass'){
  188.    $forgotpassword = $_POST['forgotpassword'];
  189.    
  190.    $randomcode = $db->random_string();
  191.    
  192.    
  193.    $hash = $db->hashSSHA($randomcode);
  194.           $encrypted_password = $hash["encrypted"]; // encrypted password
  195.           $salt = $hash["salt"];
  196.     $subject = "Password Recovery";
  197.            $message = "Hello User,\n\nYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.\n\nRegards,\nLearn2Crack Team.";
  198.             $from = "contact@Digitalnet.com";
  199.             $headers = "From:" . $from;
  200.    if ($db->isUserExisted($forgotpassword)) {
  201.    
  202.    $user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
  203.    if ($user) {
  204.            $response["success"] = 1;
  205.             mail($forgotpassword,$subject,$message,$headers);
  206.            echo json_encode($response);
  207.    }
  208.    else {
  209.    $response["error"] = 1;
  210.    echo json_encode($response);
  211.    }
  212.    
  213.    
  214.               // user is already existed - error response
  215.            
  216.            
  217.           }
  218.              else {
  219.    
  220.               $response["error"] = 2;
  221.               $response["error_msg"] = "User not exist";
  222.                echo json_encode($response);
  223.                  echo '{"success":0,"error_message":"Username and/or password is invalid."}';
  224.    
  225.    }
  226.    
  227.    }
  228.    else if ($tag == 'register') {
  229.           // Request type is Register new user
  230.           $fname = $_POST['fname'];
  231.    $lname = $_POST['lname'];
  232.           $email = $_POST['email'];
  233.    $uname = $_POST['uname'];
  234.           $password = $_POST['password'];
  235.    
  236.    
  237.          
  238.             $subject = "Registration";
  239.            $message = "Hello $fname,\n\nYou have sucessfully registered to our service.\n\nRegards,\nAdmin.";
  240.             $from = "contact@Digitalnet.com";
  241.             $headers = "From:" . $from;
  242.    
  243.           // check if user is already existed
  244.           if ($db->isUserExisted($email)) {
  245.               // user is already existed - error response
  246.               $response["error"] = 2;
  247.               $response["error_msg"] = "User already existed";
  248.               echo json_encode($response);
  249.           }
  250.              else if(!$db->validEmail($email)){
  251.               $response["error"] = 3;
  252.               $response["error_msg"] = "Invalid Email Id";
  253.               echo json_encode($response);            
  254.    }
  255.    else {
  256.               // store user
  257.               $user = $db->storeUser($fname, $lname, $email, $uname, $password);
  258.               if ($user) {
  259.                   // user stored successfully
  260.               $response["success"] = 1;
  261.               $response["user"]["fname"] = $user["firstname"];
  262.               $response["user"]["lname"] = $user["lastname"];
  263.               $response["user"]["email"] = $user["email"];
  264.       $response["user"]["uname"] = $user["username"];
  265.               $response["user"]["uid"] = $user["unique_id"];
  266.               $response["user"]["created_at"] = $user["created_at"];
  267.                  mail($email,$subject,$message,$headers);
  268.              
  269.                   echo json_encode($response);
  270.               } else {
  271.                   // user failed to store
  272.                   $response["error"] = 1;
  273.                   $response["error_msg"] = "JSON Error occured in Registartion";
  274.                   echo json_encode($response);
  275.               }
  276.           }
  277.       } else {
  278.            $response["error"] = 3;
  279.            $response["error_msg"] = "JSON ERROR";
  280.           echo json_encode($response);
  281.       }
  282.    } else {
  283.       echo "Digitalnet API";
  284.    }
  285.    ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement