0
我正在使用Swift 3.0構建一個應用程序用於學習目的。 其中一個功能是從(到)SQL Server數據庫表中提取和保存數據。其中一列是將IMAGE(照片)存儲在表中:表中的數據類型是Image(system.Byte[]
)SQL Server。如何通過web api在swift中將圖像保存到數據庫表
我可以通過Web API的照片欄,並顯示在圖像組件是這樣的:
let encodedImageData = My web api url
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros)
let image = UIImage(data: imageData)
let imageView.image = image
我有問題,將圖像保存到通過網絡API數據庫(可以節省等欄目,但有問題與圖像列)。 我試過這個:
let data = UIImagePNGRepresentation(image) as NSData?
但失敗。
我的web API和如下調用:
func post(parameters : Dictionary<String, String>, urlString : String) {
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)
let task = session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error: \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
let success = json["success"] as? Int // Okay, the `json` is here, let's get the value for 'success' out of it
print("Success: \(success)")
} else {
let jsonStr = String(data: data, encoding: .utf8) // No error thrown, but not dictionary
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError) // Log the error thrown by `JSONObjectWithData`
let jsonStr = String(data: data, encoding: .utf8)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
@IBAction func insert(){
let imageData = UIImagePNGRepresentation(myimageview.image!) as NSData?
post(parameters: ["Name": nametxt.text!,"Address": addresstxt.text!,"photoname": photonametxt.text!,"photo": String(describing: imageData),"url": urltxt.text! ], urlString: "http://XXXXXXX/api/myfavorites")
}
有人可以幫助我在斯威夫特看看圖片保存方法,數據庫中的表?
請出示您的Web API調用的代碼;還告訴我們在哪個(傳輸)格式的Web服務器期望的圖像數據 –
@AndreasOetjen:我已經添加了網頁api。在Web服務器SQL Server數據庫表中,image(photo)列是IMAGE格式 - Byte []。謝謝! – user7505698
服務器有任何錯誤返回嗎? – Terence