2017-01-27 181 views
2

首先,我不認爲這是可能的,但我有一段代碼,它向數據庫發送了請求,並且我想根據發佈的數據得到響應。我的意思是,如果變量放在db中,響應將是「ok」,否則它將是「no」。發佈回覆請求後

我的崗位要求如下:

let postDataURL = "https://www.webpage.com/login_app.php" 
let url: NSURL = NSURL(string: postDataURL)! 
let request: NSMutableURLRequest = NSMutableURLRequest(url:url as URL) 

let paramString = "precio=\(precio)&texto=\(texto)&user=\(user)&l_origen=\(l_origen)&l_destino=\(l_destino)&num_pal=\(num_pal)" 
request.httpMethod = "POST" 
request.httpBody = paramString.data(using: String.Encoding.utf8) 

NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: OperationQueue.main) { (response, data, error) in 
    print(response!) 

    if let httpResponse = response as? HTTPURLResponse { 
     let statusCode = httpResponse.statusCode 

     if statusCode==200 { 
      print("Connection Successful")  
     } else { 
      print("Connection Failed (!200)") 
     } 
    } 
} 

然後,在php身邊,我也有類似

if (affected_rows > 0){ 
    $response = "ok"; 
} else { 
    $response = "no"; 
} 

但在那之後,我不知道怎麼會PHP代碼重新連接到設備給它的迴應。

非常感謝你的時間。

編輯

響應失敗時發送:

Optional(<!DOCTYPE html> 

<html> 
<head> 
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Log in - Siens Translation</title> 

. 
. 
. 

</body> 
</html> 
) 

基本上是在網頁的HTML部分。

PHP部分

<!DOCTYPE html> 

<?php 
require "class.logsys.php"; 

header('Content-Type: text/html; charset=utf-8'); 
ini_set('default_charset', 'utf-8'); 

error_reporting(E_ERROR | E_WARNING | E_PARSE); 

session_start(); 
\Fr\LS::init(); 

if(isset($_POST['action_login'])){ 
    $identification = $_POST['login']; 
    $password = $_POST['password']; 
    if($identification == "" || $password == ""){ 
    $msg = array("Error", "Username/Password Wrong !"); 
    }else{ 
    $login = \Fr\LS::login($identification, $password,  isset($_POST['remember_me'])); 
    if($login === false){ 
     $msg = array("Error", "Username/Password Wrong !"); 
    }else if(is_array($login) && $login['status'] == "blocked"){ 
     $msg = array("Error", "Too many login attempts. You can attempt login  after ". $login['minutes'] ." minutes (". $login['seconds'] ." seconds)"); 
    } 
    } 
} 


    $precio = $_POST['precio']; 

    $texto = $_POST['texto']; 

    $texto_ant = $_POST['texto_ant']; 

    $user = $_POST['user']; 

    $pass = $_POST['pass']; 

    $l_origen = $_POST['l_origen']; 

    $l_destino = $_POST['l_destino']; 

    $num_pal = $_POST['num_pal']; 

    $modificado = $_POST['modificado']; 

$login = \Fr\LS::login($user, $pass, false, false); 
if($login === true){ 

define('HOST',''); 
define('USER',''); 
define('PASS',''); 
define('DB',''); 

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect'); 

mysqli_set_charset($con, 'utf8'); 

if($modificado!='Si'){ 

$sql = "UPDATE users SET precio='$precio', text_cli='$texto',  l_origen='$l_origen', l_destino='$l_destino', num_pal='$num_pal' WHERE  username='$user' AND text_cli='' LIMIT 1 "; 
    mysqli_query($con,$sql); 
    echo '{"success":true}'; 

if(mysqli_affected_rows($con)==0){ 
    $sql2 = "UPDATE users SET precio2='$precio', text_cli2='$texto', l_origen2='$l_origen', l_destino2='$l_destino', num_pal2='$num_pal' WHERE username='$user' AND text_cli2='' LIMIT 1 "; 
    mysqli_query($con,$sql2); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql3 = "UPDATE users SET precio3='$precio', text_cli3='$texto',  l_origen3='$l_origen', l_destino3='$l_destino', num_pal3='$num_pal' WHERE  username='$user' AND text_cli3='' LIMIT 1 "; 
    mysqli_query($con,$sql3); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql4 = "UPDATE users SET precio4='$precio', text_cli4='$texto', l_origen4='$l_origen', l_destino4='$l_destino', num_pal4='$num_pal' WHERE username='$user' AND text_cli4='' LIMIT 1 "; 
    mysqli_query($con,$sql4); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql5 = "UPDATE users SET precio5='$precio', text_cli5='$texto', l_origen5='$l_origen', l_destino5='$l_destino', num_pal5='$num_pal' WHERE username='$user' AND text_cli5='' LIMIT 1 "; 
    mysqli_query($con,$sql5); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql6 = "UPDATE users SET precio6='$precio', text_cli6='$texto', l_origen6='$l_origen', l_destino6='$l_destino', num_pal6='$num_pal' WHERE username='$user' AND text_cli6='' LIMIT 1 "; 
    mysqli_query($con,$sql6); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql7 = "UPDATE users SET precio7='$precio', text_cli7='$texto', l_origen7='$l_origen', l_destino7='$l_destino', num_pal7='$num_pal' WHERE username='$user' AND text_cli7='' LIMIT 1 "; 
    mysqli_query($con,$sql7); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql8 = "UPDATE users SET precio8='$precio', text_cli8='$texto', l_origen8='$l_origen', l_destino8='$l_destino', num_pal8='$num_pal' WHERE username='$user' AND text_cli8='' LIMIT 1 "; 
    mysqli_query($con,$sql8); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql9 = "UPDATE users SET precio9='$precio', text_cli9='$texto', l_origen9='$l_origen', l_destino9='$l_destino', num_pal9='$num_pal' WHERE username='$user' AND text_cli9='' LIMIT 1 "; 
    mysqli_query($con,$sql9); 
} 

if(mysqli_affected_rows($con)==0) { 
    $sql10 = "UPDATE users SET precio10='$precio', text_cli10='$texto', l_origen10='$l_origen', l_destino10='$l_destino', num_pal10='$num_pal' WHERE username='$user' AND text_cli10='' LIMIT 1 "; 
    mysqli_query($con,$sql10); 
    echo '{"success":false}'; 
} 

$sql11 = "UPDATE users SET text_cli='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli='' AND role='trad_app') LIMIT 1 "; 

mysqli_query($con,$sql11); 

if(mysqli_affected_rows($con)==0){ 
    $sql12 = "UPDATE users SET text_cli2='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli2='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql12); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql13 = "UPDATE users SET text_cli3='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli3='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql13); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql14 = "UPDATE users SET text_cli4='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli4='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql14); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql15 = "UPDATE users SET text_cli5='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli5='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql15); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql16 = "UPDATE users SET text_cli6='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli6='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql16); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql17 = "UPDATE users SET text_cli7='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli7='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql17); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql18 = "UPDATE users SET text_cli8='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli8='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql18); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql19 = "UPDATE users SET text_cli9='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli9='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql19); 
} 

if(mysqli_affected_rows($con)==0){ 
    $sql20 = "UPDATE users SET text_cli10='$texto' WHERE ((l_origen='$l_origen' || l_origen2='$l_origen') AND l_destino='$l_destino' AND text_cli10='' AND role ='trad_app') LIMIT 1 "; 
    mysqli_query($con,$sql20); 
} 

} 

if($modificado=='Si'){ 
    $sql = "UPDATE users SET `text_cli`='$texto', `l_origen` = '$l_origen', `precio` = '$precio', `l_destino` = '$l_destino', `num_pal` = '$num_pal' WHERE text_cli = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli2`='$texto', `l_origen2` = '$l_origen', `precio2` = '$precio', `l_destino2` = '$l_destino', `num_pal2` = '$num_pal' WHERE text_cli2 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli3`='$texto', `l_origen3` = '$l_origen', `precio3` = '$precio', `l_destino3` = '$l_destino', `num_pal3` = '$num_pal' WHERE text_cli3 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli4`='$texto', `l_origen4` = '$l_origen', `precio4` = '$precio', `l_destino4` = '$l_destino', `num_pal4` = '$num_pal' WHERE text_cli4 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli5`='$texto', `l_origen5` = '$l_origen', `precio5` = '$precio', `l_destino5` = '$l_destino', `num_pal5` = '$num_pal' WHERE text_cli5 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli6`='$texto', `l_origen6` = '$l_origen', `precio6` = '$precio', `l_destino6` = '$l_destino', `num_pal6` = '$num_pal' WHERE text_cli6 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli7`='$texto', `l_origen7` = '$l_origen', `precio7` = '$precio', `l_destino7` = '$l_destino', `num_pal7` = '$num_pal' WHERE text_cli7 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli8`='$texto', `l_origen8` = '$l_origen', `precio8` = '$precio', `l_destino8` = '$l_destino', `num_pal8` = '$num_pal' WHERE text_cli8 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli9`='$texto', `l_origen9` = '$l_origen', `precio9` = '$precio', `l_destino9` = '$l_destino', `num_pal9` = '$num_pal' WHERE text_cli9 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET `text_cli10`='$texto', `l_origen10` = '$l_origen', `precio10` = '$precio', `l_destino10` = '$l_destino', `num_pal10` = '$num_pal' WHERE text_cli10 = '$texto_ant' AND `role` = ''"; 
    mysqli_query($con,$sql); 
    } 

$sql = "UPDATE users SET text_cli='$texto' WHERE text_cli = '$texto_ant' AND `role` = 'trad_app' "; 

mysqli_query($con,$sql); 

if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli2='$texto' WHERE text_cli2 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli3='$texto' WHERE text_cli3 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli4='$texto' WHERE text_cli4 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli5='$texto' WHERE text_cli5 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli6='$texto' WHERE text_cli6 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli7='$texto' WHERE text_cli7 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli8='$texto' WHERE text_cli8 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli9='$texto' WHERE text_cli9 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

    if(mysqli_affected_rows($con)==0){ 
    $sql = "UPDATE users SET text_cli10='$texto' WHERE text_cli10 = '$texto_ant' AND `role` = 'trad_app' "; 
    mysqli_query($con,$sql); 
} 

} 

mysqli_close($con); 

    } 

?> 

<html> 
<head> 
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11"> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Log in - Siens Translation</title> 
    <link rel="icon" href="ordenador/ingles/css_imagenes/favicon.ico" type="image/x-icon" /> 
    <link rel="shortcut icon" href="ordenador/ingles/css_imagenes/favicon.ico" type="image/x-icon" /> 
    <link href="ordenador/ingles/nuestra_firma_estilos.css" rel="stylesheet" type="text/css"> 
    <link href="ordenador/ingles/css/style4.css" rel="stylesheet" type="text/css"> 
    <link href="movil/castellano/menu/menu.css" rel="stylesheet" type="text/css"> 
    <link href="ordenador/ingles/css_resolutions/resolution800x600.css" rel="stylesheet" type="text/css"> 
    <link href="ordenador/ingles/css_resolutions/resolution1024x600.css" rel="stylesheet" type="text/css"> 
    <link href="ordenador/ingles/css_resolutions/resolution1366x768.css" rel="stylesheet" type="text/css"/> 
    <link href="ordenador/ingles/css_resolutions/resolution1280x600.css" rel="stylesheet" type="text/css"/> 
    <link href="ordenador/castellano/area_clientes/css/css_login.css" rel="stylesheet" type="text/css"> 
    <link href="movil/castellano/menu/fonts.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 


<div class="menu_bar" style="font-family:'Gotham-Bold';"> 
<a class="bt-menu" style="font-size:600%; font-family:'Gotham-Bold'"><span  class="icon-menu"></span>Siens App<br><p style="font-size:25%; font- family:'Gotham-Light';">From</p></a> 
</div> 

<div id="login"> 
    <div id="centrar_app"> 
    <form action="login_app.php" method="POST" style="margin:0px auto;display:table;"> 
    <label> 
     <p style="font-size:600%">Log in </p><br><br><br> 
    </label> 
    <label> 
     <p style="font-size:400%">Username</p><br> 
     <input style="padding-left:15px; border: 2px solid #475678; font-size:200%; height:100%" id="cuadro" name="login" type="text" value="<?php if(isset($_GET['user'])){ $user = $_GET['user']; echo $user; } ?>" /> 
    </label><br><br><br> 
    <label> 
     <p style="font-size:400%">Password</p><br> 
     <input style="padding-left:15px; border: 2px solid #475678; font-size:200%; height:100%" id="cuadro" name="password" type="password" value="<?php if(isset($_GET['pass'])){ $pass = $_GET['pass']; echo $pass; } ?>" /> 
    </label><br><a style="color:white; text-decoration:underline" href="ordenador/castellano/area_clientes/forgotpass.php">Forgot password?</a><br><br> 
    <label> 
     <p> 
     <input type="checkbox" name="remember_me" /> Remember me 
     </p> 
    </label><br> 
    <div clear></div> 
    <button id="login-button" style="font-size:400%;" 
      name="action_login">Access</button><br><br> 
    </form> 

    <style> 
    input[type=text], input[type=password]{ 
     width: 230px; 
    } 
    </style> 

    <button id="login-button" style="font-size:400%" 
      onclick="location.href='';">Register</button><br><br> 
    <div id="thawteseal" style="text-align:center;" title="Click to Verify - This site chose Thawte SSL for secure e-commerce and confidential communications."> 
    <div><script type="text/javascript" src="https://seal.thawte.com/getthawteseal?host_name=&amp;size=S&amp;lang=en"></script></div> 
    </div> 
    </div> 
</div> 

<div id="login"> 
    <div id="centrar_app"> 
    <a onMouseOver="this.style.color='white'">If you can't access our payment zone Gateway, you need to deactivate "Block Cookies" in your iPhone configuration settings.</a> 
</div> 
</div> 

<div style="margin-top:10rem" align="center"> 
<img style="width: 20%; height: 20%" src=""> 
</div> 

+2

它根本不需要*「重新連接」,POST不會隨時隨地發生,您的服務器有機會按照自己的意願進行操作。它可以簡單地回覆你想要的東西,它將成爲'response'或'data'的一部分。 – luk2302

+0

@ luk2302爲什麼不做出這個答案? – Steeve

+0

@Steeve,因爲我可以更快地輸入評論,並且不必對寫作保持謹慎 - 儘管如此,我現在發佈了一個答案。 – luk2302

回答

1

下面是使用URLSession一個例子:

PHP側:

if (affected_rows > 0) { 
    echo '{"success":true}'; 
}else{ 
    echo '{"success":false}'; 
} 

夫特側:

let url=URL(string: "https://www.webpage.com/login_app.php"); 
    var request=URLRequest(url:url!) 
    request.httpMethod="POST" 
    let postString = "precio=\(precio)&texto=\(texto)"; 
    request.httpBody = postString.data(using: String.Encoding.utf8); 

    let task=URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in 
     guard data != nil else { 
      print("no data found") 
      return 
     } 

     do{ 
      if let jsonData=try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary{ 
       print(jsonData) 
       let success=jsonData.value(forKey: "success") as! Bool 
       if success{ 
        print("login succeded") 
       }else{ 
        print("login failed") 
       } 
      }else{ 
       print("could not parse json") 
       let json_str=NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
       print("Failed to parse json:", json_str) 
      } 
     }catch{ 
      print("request failed") 
      let json_str=NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
      print(json_str) 
     } 
    }) 
    task.resume() 

-edit 因爲它不工作,請嘗試更改您的POST請求是這樣的:

let url=URL(string: "https://www.webpage.com/login_app.php") 
var request=URLRequest(url:url!) 
request.httpMethod="POST" 
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") 
let params=["precio":precio, "texto":texto] 
let body=NSMutableData() 
for (key, value) in params { 
    body.appendString("--\(boundary)\r\n") 
    body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") 
    body.appendString("\(value)\r\n") 
} 
request.httpBody=body 

-EDIT2 這是我的NSMutableData擴展:

extension NSMutableData { 
    func appendString(_ string: String) { 
     let data = string.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: true) 
     append(data!) 
    } 
} 
+0

這基本上是一個鏈接專用的答案,請在此答案中包含相關答案的相關部分,或投票結束此問題爲重複。如果其他答案被刪除,這個答案也將是無用的(不是你想要的) – luk2302

+0

我編輯了我的答案@ luk2302 –

+0

非常感謝你的回答,我會嘗試一下代碼。 – alberzyzz

3

你服務器根本不需要「重新連接」設備/客戶端,POST不會被遺忘。客戶端與發送請求並等待服務器響應的服務器有開放連接。

你的服務器有機會做你想要的。它可以簡單地回覆你想要的結果 - 該結果將在sendAsynchronousRequest的回調中成爲responsedata的一部分。現在你的php代碼沒有打印任何東西,但是嘗試echo的東西,在swift回調中設置一個斷點,並檢查回調對象包含的內容以及它們與你在服務器上編輯的內容有什麼關係。

+0

非常感謝你的回答 – alberzyzz