我正在进行网络调用,以将图像上传到后端服务器。现在我正在使用以下代码。此代码适用于互联网在线的条件。
// MARK: - PUT
static func PUT(URL: String,
data: Data,
mimeType: String,
headers: [String: String]?) -> Promise<Void>
{
return Promise { fulfill, reject in
let URL = try! URLRequest(url: URL, method: .put, headers: headers)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(InputStream.init(data: data), withLength: UInt64(data.count), name: "image", fileName: "file.png", mimeType: mimeType)
},
with: URL,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.value == nil {
fulfill()
}else {
reject(response.result.error!)
}
}
case .failure( _):
break
}
})
}
}
}
如果我将其置于离线模式。它仍然会执行该功能并仍然满足()承诺。即使网络处于脱机状态。我认为这是因为它检查encodingResult是否成功。 NOt用于网络呼叫本身。
我如何检查网络通话是否成功?它正在回归虚空。
导入便笺:
答案 0 :(得分:4)
如果您要使用状态代码来确定成功或失败,则应添加validate
:
例如:
static func PUT(URL: String,
data: Data,
mimeType: String,
headers: [String: String]?) -> Promise<Void> {
return Promise { fulfill, reject in
let URL = try! URLRequest(url: URL, method: .put, headers: headers)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
}, with: URL) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload
.validate(statusCode: 200 ..< 300)
.responseJSON { response in
switch response.result {
case .success:
fulfill()
case .failure(let error):
reject(error)
}
}
case .failure(let error):
reject(error)
}
}
}
}
以上假设成功响应后,您还会获得JSON响应。您可能需要对value
进行一些额外检查。
如果您在成功时未返回JSON,则只需使用response
,而不是responseJSON
:
static func PUT(URL: String,
data: Data,
mimeType: String,
headers: [String: String]?) -> Promise<Void> {
return Promise { fulfill, reject in
let URL = try! URLRequest(url: URL, method: .put, headers: headers)
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(data, withName: "image", fileName: "file.png", mimeType: mimeType)
}, with: URL) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload
.validate(statusCode: 200 ..< 300)
.response { response in
if let error = response.error {
reject(error)
} else {
fulfill()
}
}
case .failure(let error):
reject(error)
}
}
}
}