我多年来一直在与此作斗争。我正在尝试将图像上传到服务器但仍然出现500错误。
这是我用来获取图像的代码,base64对其进行编码,然后将其添加到字典中。
if let imageDataToUpload = UIImageJPEGRepresentation(selectedImage, 1.0) {
let encodedImageData = imageDataToUpload.base64EncodedString(options: [])
let extras = "data:image/jpeg;base64,"
let postBody = [
"image": extras + encodedImageData,
"id": id,
"instruction": "1",
"ext": ""
]
let endPoint = UrlFor.uploadPhoto
ApiManager().apiPostImage(endPoint: endPoint, postBody: postBody, callBackFunc: handleResultOfUploadPhoto) }
这是我用来执行实际POST请求的代码。您会注意到我正在尝试将帖子主体转换为JSON对象。
func apiPostImage(endPoint: String, postBody: [String: Any]?, callBackFunc: @escaping (ResultOfApiCall) -> Void) {
// get the sessionKey
guard let sessionKey = KeyChainManager().getSessionKey() else {
print("error getting session key")
AppDelegate().signUserOut()
return
}
// create a url with above end point and check its a valid URL
guard let url = URL(string: endPoint) else {
print("Error: cannot create URL")
return
}
// set up the request
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
if let postBody = postBody {
do {
try urlRequest.httpBody = JSONSerialization.data(withJSONObject: postBody, options: [])
} catch {
print("problems creating json body")
}
}
// set up the header
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept": "application/json",
"apiKey": "0101010-0101010", // not the real apiKey
"usrKey": sessionKey,
"appInfo" : "appcode:1000|version:2.0.37",
"Content-Type": "application/json"
]
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest, completionHandler:
{ (data: Data?, response: URLResponse?, error: Error?) -> Void in
let (noProblem, ResultOfCall) = self.checkIfProblemsWith(data: data, response: response, error: error)
guard noProblem else {
callBackFunc(ResultOfCall)
return
}
let serializedData: [String:Any]
do {
// safe bc checked for nil already.
serializedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
} catch {
callBackFunc(ResultOfApiCall.errorWhileSerializingJSON)
return
}
// pass serialized data back using the callBackFunc
callBackFunc(ResultOfApiCall.success(serializedData))
})
task.resume()
}
API是RESTful。我无法访问API错误日志,但我从API中收到此错误:
["codesc": GENERALERROR, "code": 5001, "msg": Conversion from string "Optional(1004007)" to type 'Double' is not valid.]
答案 0 :(得分:0)
500内部服务器错误是服务器端错误,这意味着问题可能与您的计算机或互联网连接无关,而是网站服务器的问题。
答案 1 :(得分:0)
好的,我明白了。感谢@Scriptable推动我深入挖掘返回的错误消息。
似乎API期望其中一个属性的双重,即id属性,但我传入了一个String。
我还必须将postBody字典从可选字段更改为非可选字段。
更改了此问题并解决了问题。
答案 2 :(得分:0)
var task = URLSession().uploadTask(with: urlRequest, from: imageData) { (data , response , error) in
// Check Response here
})
task.resume()
您发送的数据是可选值,请确保您传递的数据不是可选值。