Monday, April 4, 2016

Multiple calls to a Alamofire request, get reference for each call

Leave a Comment

I have used Alamofire for uploading images in multipart form data. I am successful in achieving my target. Each time I upload an image, I call the "uploadDocWebService" function. So the number of times the function is called, is equal to the number of images. I am hopeless in identifying the result of each call. My images are uploaded successfully. In case there is a server failure, or internet connection failure the uploading fails, I cannot identify which image I should delete from the view, that has failed. I pass indexPath as a parameter for each image upload. But that indexPath updates to the latest image upload before I receive the result for the first image upload. Can any one suggest me a better approach for this situation.

Here is the code I use for image upload:

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)             }         }     )  } 

If I get to know the which result is associated to which call, that could help me delete that particular image from view.

1 Answers

Answers 1

You need to keep a reference to the original request, should be the same for upload requests I think. Try the following:

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

Then you can simply have an array of requests i.e: var requests: [Request](). When calling Alamofire.upload / Alamofire .request - it returns a Request object.

You can then do:

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

Then you can just loop through the array and check whatever request you wish.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment