1
\$\begingroup\$

I am uploading an array of photos to the server (using Alamofire):

func uploadImages() {
  for card in cards! {
        let photo = card.media
        func onSuccess(jsonData: Any?) {
            photoCount += 1
            SVProgressHUD.dismiss()
            if let jsonData = jsonData { // unwrapping
                let json = JSON(jsonData)
                let photoAttr = photoAttributes(from: json)
                var photoStoryAttrElement = [String : AnyObject]()
                photoStoryAttrElement["photos_attributes"] = photoAttr as AnyObject
                photoStoryAttrElement["name"] = "Photo : \(photoCount)" as AnyObject
                if let placeID = card.location?.placeId {
                    let locationAttr = ["place_id" : placeID]
                    photoStoryAttrElement["location_attributes"] = locationAttr as AnyObject
                }

                if let caption = card.caption {
                    photoStoryAttrElement["description"] = caption  as AnyObject
                }
                photoStoryArray.append(photoStoryAttrElement)
            }

            if photoCount <= cards!.count {
                SVProgressHUD.show(withStatus: "Uploading Photo \(photoCount) of \(String(describing: cards!.count))")
            } else {
                uploadArticle(photoStories: photoStoryArray)
            }

            if jsonData != nil { // Unwrapping
            } else { // no value returned from response
                //                no value returned
            }

        }
        func onFailure(err: Error) {
            SVProgressHUD.dismiss()
            print("Failed to Upload image. Error: \(err)")
        }
        if photoCount == 1 {
            SVProgressHUD.show(withStatus: "Uploading Photo 1 of \(String(describing: cards!.count))")
        }
        uploadImage(image: photo!, imageKey: "photos[photo]", imageName: "filename", location_id: nil, location_place_id: nil, urlString: Constants.URL.kUploadPhoto, method: .post, param: nil, onSuccess: onSuccess, onFailure: onFailure)
    }

}

This function keeps counting till all photos are uploaded successfully and then calls another function uploadArticle(). Is there a better way to do it?

\$\endgroup\$
  • \$\begingroup\$ If you ever run the program again, won't it restart the count at 1? Or does this never happen? \$\endgroup\$ – Barry Carter Nov 3 '17 at 16:29
  • \$\begingroup\$ @BarryCarter The counter is reset properly before calling this function \$\endgroup\$ – sasquatch Nov 3 '17 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.