我正在尝试上传uiview(图表),但我在电子邮件中收到空图片(来自webservice)... Android正在运行
UIGraphicsBeginImageContext(self.view.bounds.size);
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let jpegCompressionQuality: CGFloat = 1
let imgData:Data = UIImageJPEGRepresentation(screenShot!,jpegCompressionQuality)!
let lengthOfData = imgData.count
let strBase64 = imgData.base64EncodedString(options: [])
var request = URLRequest(url: URL(string: "http://myws.com/Chart.php")!)
request.httpMethod = "POST"
let postString = "data=\(strBase64)&email=admin@myws.com"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length")
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
答案 0 :(得分:0)
您拍摄iOS设备屏幕截图的代码很好。我认为您将UIImage上传到服务器的帖子请求缺少以下内容:
let imgData:NSData = data
let lengthOfData = imgData.length
// ENCODINGDATA - whatever encoding your server wants here
request.addValue(ENCODINGDATA, forHTTPHeaderField: "Content-Type")
request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length")
除此之外,最好使用AlamoFire
来处理这样的复杂服务器任务。它使它更容易。它可以这样做
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
随意建议编辑以使其更好。如果我的回答中有任何错误或缺点,请告诉我