I am unable to upload an image using swift. All the other information is inserted correctly into the database. This function submit book details but it also needs to submit an image. How do I submit an image using my current swift code? Thanks.
我无法使用swift上传图片。所有其他信息都正确插入数据库。此功能提交书籍详细信息,但也需要提交图像。如何使用我当前的快速代码提交图像?谢谢。
func uploadOrder (completion: @escaping (Bool, Any?, Error?) -> Void) {
let imageSize: CGSize = (self._book.imageView?.bounds.size)!
UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
let context = UIGraphicsGetCurrentContext()
self._book.imageView?.layer .render(in: context!)
let myImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
let imageData: NSData = UIImageJPEGRepresentation(myImage, 90)! as NSData
UIGraphicsEndImageContext()
let jsonDictionary = NSMutableDictionary()
guard let url = URL(string: Constants.uploadOrder) else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
if let isbn = self._book.ISBN as String? {
jsonDictionary.setValue(isbn, forKey:"isbn")
} else {
jsonDictionary.setValue("", forKey:"isbn")
}
guard let httpBody = try? JSONSerialization.data(withJSONObject: jsonDictionary, options: []) else {
return
}
urlRequest.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: urlRequest) { (data, response, error) in
if let response = response {
print("Response", response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let status = (json as AnyObject).value(forKey:"OK") as! Bool? {
DispatchQueue.main.async { //GUI thread
completion(true, status, nil)
}
}
} catch let error {
print(error.localizedDescription)
DispatchQueue.main.async { //GUI thread
completion(false, nil, error)
}
}
}
}.resume()
}
1 个解决方案
#1
1
You could convert your image data to base64
您可以将图像数据转换为base64
let base64String = imageData!.base64EncodedString(options: .lineLength64Characters)
and add it as value for a key to your jsonDictionary
并将其添加为jsonDictionary的键的值
jsonDictionary.setValue(base64String, forKey:"image")
#1
1
You could convert your image data to base64
您可以将图像数据转换为base64
let base64String = imageData!.base64EncodedString(options: .lineLength64Characters)
and add it as value for a key to your jsonDictionary
并将其添加为jsonDictionary的键的值
jsonDictionary.setValue(base64String, forKey:"image")