2015-05-14 102 views
0

我正在開發一個帶有Swift的iOS應用,它應該根據用戶的位置從MySQL數據庫中獲取一些數據。我不知道PHP,我無法找到解釋如何從應用程序接收數據的資源。PHP:如何從JSON獲取變量(從Swift iOS應用發送)並用JSON響應

我有這樣的PHP代碼:

<?php 

// Create connection 
$con=mysqli_connect("localhost","*******","*******","*******"); 

// Check connection 
if (mysqli_connect_errno()) 
{ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// This SQL statement selects ALL from the table 'Locations' 
$sql = "SELECT * FROM *******"; 

// Check if there are results 
if ($result = mysqli_query($con, $sql)) 
{ 

    // If so, then create a results array and a temporary one 
    // to hold the data 
    $resultArray = array(); 
    $tempArray = array(); 

    // Loop through each row in the result set 
    while($row = $result->fetch_object()) 
    { 
     // Add each row into our results array 
     $tempArray = $row; 
     array_push($resultArray, $tempArray); 
    } 

    // Finally, encode the array to JSON and output the results 
    echo "{ \"posts\": "; 
    echo json_encode($resultArray); 
    echo "}"; 
} 

// Close connections 
mysqli_close($con); 
?> 

,你可以看到,當它被調用它從表中獲取的所有數據,並返回它作爲一個JSON。我要做的下一步是從斯威夫特應用程序發送我的位置,此代碼:

@IBAction func submitAction(sender: AnyObject) { 

      //declare parameter as a dictionary which contains string as key and value combination. 
      var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String> 

      //create the url with NSURL 
      let url = NSURL(string: "http://myServerName.com/api") //change the url 

      //create the session object 
      var session = NSURLSession.sharedSession() 

      //now create the NSMutableRequest object using the url object 
      let request = NSMutableURLRequest(URL: url!) 
      request.HTTPMethod = "POST" //set http method as POST 

      var err: NSError? 
      request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body 

      request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
      request.addValue("application/json", forHTTPHeaderField: "Accept") 

      //create dataTask using the session object to send data to the server 
      var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
       println("Response: \(response)") 
       var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
       println("Body: \(strData)") 
       var err: NSError? 
       var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary 

       // Did the JSONObjectWithData constructor return an error? If so, log the error to the console 
       if(err != nil) { 
        println(err!.localizedDescription) 
        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) 
        println("Error could not parse JSON: '\(jsonStr)'") 
       } 
       else { 
        // The JSONObjectWithData constructor didn't return an error. But, we should still 
        // check and make sure that json has a value using optional binding. 
        if let parseJSON = json { 
         // Okay, the parsedJSON is here, let's get the value for 'success' out of it 
         var success = parseJSON["success"] as? Int 
         println("Succes: \(success)") 
        } 
        else { 
         // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? 
         let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) 
         println("Error could not parse JSON: \(jsonStr)") 
        } 
       } 
      }) 

      task.resume() 
     } 

禮貌從http://jamesonquave.com/blog/making-a-post-request-in-swift/

,我不知道該怎麼「搞定」(接受,什麼功能使用)此JSON:

{"items": [ 
      { 
       "minLat": "43.000000", 
       "maxLat": "44.000000", 
       "minLon": "-79.000000", 
       "maxLon": "-78.000000", 
      } 
      ] 
    } 

從應用程序,以便在PHP這樣的事情:

$minLat = $json['minLat']; 
$maxLat = $json['maxLat']; 
$minLon = $json['minLon']; 
$maxLon = $json['maxLon']; 

$sql = "SELECT * FROM ******* WHERE latitude BETWEEN".$minLat." AND ".$maxLat." AND longitude BETWEEN ".$minLon." AND ".$maxLon; 

謝謝

+0

嗨安德烈,最簡單的方法你必須在你的服務器中創建index.php文件,並在你的swift應用程序中指定http://myServerName.com/index.php url,在php文件中獲取請求,如'if(isset( $ _POST [「your_key_here」])){$ json = json_decode($ _ POST [「your_key_here」]);}' – styopdev

+0

您需要使用Alamofire和SwiftyJSON。 –

+0

我對Swift代碼沒有問題!我用PHP –

回答

1

答案其實是非常愚蠢的,很容易:

首先沒有奏效之前我評論這兩條線:

request.addValue("application/json", forHTTPHeaderField: "Content--Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 

然後我用一個字符串,而不是一個JSON發送POST數據(它肯定工作與JSON也,但是這是在這一刻是什麼在起作用):

let request = NSMutableURLRequest(URL:myUrl!); 
request.HTTPMethod = "POST"; 

let postString = "minLat=43.0&maxLat=44.0&minLon=26.0&maxLon=27.0"; 

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding); 

,並在服務器端簡單:

$minLat = $_REQUEST["minLat"]; 
$maxLat = $_REQUEST["maxLat"]; 
$minLon = $_REQUEST["minLat"]; 
$maxLon = $_REQUEST["maxLat"]; 

:| |