我需要将image
发送到服务器并等待服务器的响应。图片很大,需要很长时间,所以我想将其并行化。我尝试了很多方法,但出现错误:
2019-12-20 15:01:49.148156 + 0100捕获照片[644:138111]任务<81527D6C-279F-4644-9F5A-DE00665BCBF2>。<18>完成,错误为[-1001]错误域= NSURLErrorDomain代码= -1001“请求超时。” UserInfo = {_ kCFStreamErrorCodeKey = -2102,NSUnderlyingError = 0x282184240 {Error Domain = kCFErrorDomainCFNetwork Code = -1001“(null)” UserInfo = {_ kCFStreamErrorCodeKey = -2102,_kCFStreamErrorDomainKey = 4}},_NSURLErrorFailingURLSessionTaskErrorKey = 6446C-A-5279 -DE00665BCBF2>。<18>,_NSURLErrorRelatedURLSessionTaskErrorKey =(“ LocalUploadTask <81527D6C-279F-4644-9F5A-DE00665BCBF2>。<18>”),NSLocalizedDescription =请求超时。
exteriorQueinAsinc.async {
let queue = OperationQueue()
for i in 0..<images.count
{
queue.addOperation {
self.sendImageToServer(image: images[i], imageName: imageNames[i])
}
}
queue.waitUntilAllOperationsAreFinished()
}
发送图像功能:
func SendImageToServer(image:UIImage,imageName:String){
let userId = AppSettings.user.id
let token = AppSettings.token
let url = "http://intaiapi.catch-system.com/vehicle_image"
guard let imageData = image.jpegData(compressionQuality: 1.0) else { return }
let parametar : [String:String] = [
"apiUrl":apiUrl,
"userId":userId!,
"userToken":token,
]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 1200
manager.upload(multipartFormData: { multipleData in
for (key, value) in parametar {
multipleData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
multipleData.append(
imageData, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg")}, to: url) {
(result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
if let image = UIImage(data: response.data!) {
handler(.success(image))
} else {
NotificationCenter.default.post(name: .ClearImageErrorNotification, object: nil)
handler(.failure(.NotValidStatusCode(response.debugDescription)))
}
}
case .failure(let encodingError):
NotificationCenter.default.post(name: .ClearImageErrorNotification, object: nil)
handler(.failure(.NotValidStatusCode(encodingError.localizedDescription)))
print(encodingError)
}
}
}
我尝试的一种方法就是这种方法。我使用Alamofire。
您可以增加等待请求完成的超时时间。设置
manager.session.configuration.timeoutIntervalForResource = 1200
或附近的任何其他值
manager.session.configuration.timeoutIntervalForRequest = 1200