2016-11-18 6 views
-1

こんにちは私は、Webサイトと通信するためにios swift 3アプリケーションを作成していますが、多くのことを行った後に、アプリケーションはfalseまたはtrueの型の値を返すべきですが、私はどこが間違っているのか、間違いを訂正する方法を教えてくれます!迅速でIOSアプリケーションで戻り値phpを読み取る

値戻り: ....応答=オプション({URL: "http://....myurl.php"} .....

SWIFT CODE

let myUrl = URL(string: "http://....myurl.php"); 

var request = URLRequest(url:myUrl!) 

request.httpMethod = "POST"// Compose a query string 

let postString = "username=James&password=Bond"; 

request.httpBody = postString.data(using: String.Encoding.utf8); 

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in 

    if error != nil 
    { 
     print("error=\(error)"); 
     // return false 
    } 

    print("response = \(response)") 

} 
task.resume() 

return 0; 

PHPコード:

include 'user.php'; 

$user = new User(); 
$username= $_REQUEST["username"]; 
$password = $_REQUEST["password"]; 

if($user->login($username,$password)==true){ 
     echo json_encode("true"); 
} 

else{ 
    echo json_encode("false"); 
} 

誤差画像:

ERROR PICTURE

答えて

1

あなたはデータではなく、応答を検討する必要があります。 そして多分あなたは例えば次のように、あなたのPHPコードであなたの戻り値をカプセル化する必要があります

if($user->login($username,$password)==true){ 
    echo '{"success":true}'; 
}else{ 
    echo '{"success":false}'; 
} 

そして迅速に結果が得られます。

func login(request_completed:@escaping (_ succeded:Bool) ->()) { 
    let myUrl=URL(string: "http://....myurl.php"); 
    var request=URLRequest(url:myUrl!) 
    request.httpMethod="POST" 
    let postString = "username=James&password=Bond"; 
    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") 
      request_completed(false) 
      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") 
        request_completed(true) 
        return 
       }else{ 
        print("login failed") 
        request_completed(false) 
        return 
       } 
      }else{ 
       print("could not parse json") 
       request_completed(false) 
      } 
     }catch{ 
      print("request failed") 
      request_completed(false) 
     } 
    }) 
    task.resume() 
} 
+0

はあなたに感謝しますが、ここで、iは、あなたの迅速なコードを挿入します? @Marie Dm –

+0

@RikiDev詳細は –

+0

で私の答えを編集しました。私のXcodeでコードコードを起動すると、構文エラーが発生しました! @マリーDm –

関連する問題