2015-05-29 138 views
1

您好我正嘗試將我的iOS應用程序連接到我的PHP API。 我發送JSON POST到我的PHP API,但我得到一個空數組作爲輸出。向PHP發送HTTP POST請求時發出空數組請求來自Swift應用程序

我的銀行代碼

@IBAction func JSONButtonAction(sender: AnyObject) { 

    var configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
    var session = NSURLSession(configuration: configuration) 
    var usr = "dsdd" 
    var pwdCode = "dsds" 

    var image : UIImage = clickedPhotoView.image! 
    var imageData = UIImagePNGRepresentation(image) 

    let base64String = imageData.base64EncodedStringWithOptions(.allZeros) 

    let params:[String: AnyObject] = [ 
     "email" : usr, 
     "image" : base64String ] 

    let url = NSURL(string:"http://localhost/app/") 
    let request = NSMutableURLRequest(URL: url!) 

    let boundaryConstant = "Boundary-7MA4YWxkTLLu0UIW"; // This should be auto-generated. 

    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 
      request.HTTPMethod = "POST" 
    var err: NSError? 
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err) 

    let task = session.dataTaskWithRequest(request) { 
     data, response, error in 

     // println("response = \(response)") 

     let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) 

     println("\(responseString)") 

     if let httpResponse = response as? NSHTTPURLResponse { 
      if httpResponse.statusCode != 200 { 
       println("response was not 200: \(response)") 
       return 
      } 
     } 
     if (error != nil) { 
      println("error submitting request: \(error)") 
      return 
     } 

     // handle the data of the successful response here 
     var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary 
     //println(result) 
    } 
    task.resume() 
} 

PHP代碼

print_r($_POST); 

輸出是

array(

) 

但是當我使用

$data = json_decode(file_get_contents('php://input'), true); 

它工作正常 我不知道爲什麼$ _POST不工作。

+1

你有沒有嘗試設置''request.HTTPBody = params'',其中params是NSData和NSASCIIStringEncoding?目前,您只是將純文本發送給http協議需要「key = value」編碼的機構。 – kekub

+0

@kekub爲我解決了這個問題! – Bijington

回答

0

如果你的意圖實際上是發送一個字符串,那麼你應該改變的內容類型:

request.setValue("text/plain", forHTTPHeaderField: "Content-Type") 

測試了確切的代碼與我的測試服務器上的這個修改:

Your code works with my server once content-type is changed

否則,請檢查@ kekub的評論。