uploadTask方法不工作URLSession Swift 3

时间:2017-04-10 21:09:59

标签: php swift xcode urlsession

我想使用URLSession类的uploadTask方法将图像发送到服务器,我有上传图像的以下功能,但我无法在php文件中读取任何内容。

AdjMatOnestep()

php文件包含以下代码:

@IBAction func uploadImage(_ sender: Any) {
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    UIApplication.shared.isNetworkActivityIndicatorVisible = true

    let url = URL(string: "http://www.localhost.com/destiny.php")!
    let file: URL = Bundle.main.url(forResource: "colors", withExtension:"jpg")!

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("image/jpeg", forHTTPHeaderField: "Content-Type")

    let task = session.uploadTask(with: request, fromFile: file) {
        (data: Data?, res: URLResponse?, error: Error?) in
        defer {
            DispatchQueue.main.async {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
            }
        }
        if error != nil {
            print(error!.localizedDescription)
            return
        }
        if data != nil{
            let strData = String(data:data!, encoding:String.Encoding.utf8)
            print(strData!)
        }
        let code = (res as! HTTPURLResponse).statusCode
        print(code)
        if code != 201 {
            print(HTTPURLResponse.localizedString(forStatusCode: code))
            return
        }
        print("Uploaded!")
    }
    task.resume()
 }

我的输出应用:

print_r($_POST)
print_r($_FILES)

我希望你能帮我找到错误。

问候。

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,为PHP解释添加了标题。