gpt4 book ai didi

swift - 如何在swift中通过web api将图像保存到数据库表

转载 作者:行者123 更新时间:2023-11-30 12:41:00 31 4
gpt4 key购买 nike

我正在使用 Swift 3.0 构建一个应用程序用于学习目的。其中一项功能是从 SQL Server 数据库表中获取数据并将其保存到其中。其中一列是在表中存储IMAGE(照片):表中的数据类型是SQL Server中的Image(system.Byte[])。

我可以通过 Web api 获取照片列并将其显示在图像组件中,如下所示:

let encodedImageData = My web api url
let imageData = NSData(base64EncodedString: encodedImageData options: .allZeros)
let image = UIImage(data: imageData)
let imageView.image = image

我在通过 Web api 将图像保存到数据库时遇到问题(可以保存其他列,但图像列有问题)。我试过这个:

let data = UIImagePNGRepresentation(image) as NSData?

但是失败了。

我的网络 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")

}

有人可以帮我看看 Swift 中图像保存到数据库表的方法吗?

最佳答案

我认为您的图像使用了错误的数据结构。您应该直接使用 base64 编码的字符串,而不是使用 NSDataString(describing:) (这绝对不会达到您想要的效果) ,如下面的代码:

@IBAction func insert(){

let imageBase64String = UIImagePNGRepresentation(myimageview.image!)?.base64EncodedString()

post(parameters: ["Name": nametxt.text!,"Address": addresstxt.text!,"photoname": photonametxt.text!,"photo": imageBase64String,"url": urltxt.text! ], urlString: "http://XXXXXXX/api/myfavorites")

}

关于swift - 如何在swift中通过web api将图像保存到数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42217913/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com