【问题标题】:Multiple calls to a Alamofire request, get reference for each call多次调用 Alamofire 请求,获取每次调用的参考
【发布时间】:2016-05-10 19:57:27
【问题描述】:

我使用 Alamofire 上传多部分表单数据中的图像。我成功地实现了我的目标。每次上传图片时,我都会调用“uploadDocWebService”函数。所以函数被调用的次数,等于图片的数量。我无法确定每次通话的结果。我的图片上传成功。如果服务器出现故障,或者互联网连接失败,上传失败,我无法确定应该从视图中删除哪个图像,该图像已失败。我将 indexPath 作为每个图像上传的参数传递。但是在我收到第一个图像上传的结果之前,那个 indexPath 会更新到最新的图像上传。任何人都可以建议我针对这种情况的更好方法。

这是我用来上传图片的代码:

func uploadDocWebservice(fileUrl: NSURL , progressView : PWProgressView , index : String , imageData : NSData? , name : String , mimeType : String , uploadType : String){

    let url = "\(kBaseURL)\(uploadDocsUrl)"

    var type = String()
    var networkGroupId = String(SingletonClass.sharedInstance.selectedNetworkId!)

    if SingletonClass.sharedInstance.groupPopUp == true {

        type = "group"
        networkGroupId = String(SingletonClass.sharedInstance.selectedSubNetworkOrGroup!)

    }else {

        type = "network"
    }

    Alamofire.upload(
        .POST,
        url,
        multipartFormData: { multipartFormData in

            if uploadType == "Image" {
                multipartFormData.appendBodyPart( data: imageData! , name: "file", fileName: name, mimeType: mimeType)
            }else {
                multipartFormData.appendBodyPart(fileURL: fileUrl, name: "file")
            }
            multipartFormData.appendBodyPart(data:"\(SingletonClass.sharedInstance.tokenId)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"token")
            multipartFormData.appendBodyPart(data:"\(type)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"networkGroup")
            multipartFormData.appendBodyPart(data:"\(networkGroupId)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"networkGroupId")

        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):

                upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in

                    let ratio: Float = Float(totalBytesRead) / Float(totalBytesExpectedToRead)
                    // Call main thread.
                    dispatch_async(dispatch_get_main_queue(), {
                        progressView.progress = ratio
                    })

                }

                upload.responseJSON { response in

                    let dataString = NSString(data: response.data!, encoding:NSUTF8StringEncoding)
                    print(dataString)

                    self.edited = true

                    do{

                        let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: .MutableLeaves) as? NSDictionary

                        if let success = json!["success"] as? Int {

                            if success == 1 {

                                let id = json!["response"]!.objectForKey("id") as! String
                                let docName = "\(json!["response"]!.objectForKey("name") as! String).\(json!["response"]!.objectForKey("ext") as! String)"
                                let dic = ["name" : docName , "Id" : id]
                                self.uploadedDocsIdArray.addObject(dic)
                                self.uploadedArrayJustNames.addObject(docName)
                                print(self.uploadedDocsIdArray)

                            }else {

                                // delete image from view here

                            }

                        }

                    }catch{

                        // delete image from view here
                        invokeAlertMethod("Error", msgBody: "Invalid Json", delegate: self)

                    }

                }
            case .Failure(let encodingError):

                print(encodingError)
            }
        }
    )

}

如果我知道哪个结果与哪个调用相关联,这可以帮助我从视图中删除该特定图像。

【问题讨论】:

  • 您需要为每张图片提供唯一的 id 或与每张图片唯一关联的东西。例如,您可以有一个单独的上传跟踪字典,其中包含图像 ID 作为键,其值作为 Bool。最初所有的值都是“假的”。每当图像 ID 的上传成功时,您都可以将该值设置为“true”。
  • 我已经试过了。如果出现连接或服务器故障,我将不会返回失败的图像 ID。失败的图像可能不止一张。
  • 您是否获得了成功上传的 image-Id ?
  • 是的,我确实可以成功上传
  • @AmritSidhu 您之前提到您会获得成功上传的图像 ID。如果仍然如此,您不需要标记请求 - 一旦您收到成功,您就会知道哪些成功了。然后,一旦所有请求都完成,您可以检查成功图像下载的集合/数组中缺少哪些。要检查多个请求何时完成,我会签出dispatch_group,以便在一组任务完成时收到通知。 RayWenderlich 有一个很好的调度组示例raywenderlich.com/63338/grand-central-dispatch-in-depth-part-2

标签: ios iphone xcode swift alamofire


【解决方案1】:

您需要保留对原始请求的引用,我认为上传请求应该相同。请尝试以下操作:

func uploadDocWebservice(fileUrl: NSURL , progressView : PWProgressView , index : String , imageData : NSData? , name : String , mimeType : String , uploadType : String) -> Request? {
    return Alamofire.upload ...
}

然后你可以简单地有一个请求数组,即: var requests: [Request]()。当调用 Alamofire.upload / Alamofire .request - 它返回一个 Request 对象。

你可以这样做:

var requests: [Request]()
let request = uploadDocWebservice(...)
requests.append(request)

然后你可以遍历数组并检查你想要的任何请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多