Advertisement
Guest User

Ios WEb Service Communication

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