多次调用Alamofire请求,获取每次通话的参考

时间:2016-02-02 06:09:21

标签: ios iphone xcode swift alamofire

我使用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)
            }
        }
    )

}

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

1 个答案:

答案 0 :(得分:3)

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

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)

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