0

This is how I am trying to upload an image using Alamofire. But the program crashes saying something like...'NSInvalidArgumentException', reason: '-[_SwiftTypePreservingNSNumber dataUsingEncoding:]: unrecognized selector sent to instance... I'm not able figure the exact reason.This is how I'm making the request...

    for i in 1...(imageArray.count) {
        for img in imageArray {

            let url = "http://myapp.com/a/images_upload"
            let headers = [ "Content-Type":"application/x-www-form-urlencoded"]

  let imageData: Data = (UIImageJPEGRepresentation(img, 0.6) as Data?)!
            print(imageData)

            let parameters: [String: Any]  = [
                    "access_token":  commonVarForAccessToken,
                    "seller_id": idForNewOldUser, 
                    "product_id": self.productId,
                    "is_default": "1",
                    "sequence": i,
                    "image": imageData  ]

            Alamofire.upload(multipartFormData: { (multipartFormData) in
                print(parameters)

                multipartFormData.append(imageData as Data, withName: "home-\(self.index)", fileName: "home-\(self.index)", mimeType: "image/jpeg")

                for (key, value) in parameters {
                    print(key,value)

                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)

                }
            }, to:url)
            { (result) in
                switch result {
                case .success(let upload, _, _):
                    upload.uploadProgress(closure: { (Progress) in
                        //Print progress
                    })
                    upload.responseJSON { response in

                        print(response.request)  // original URL request

                         if let JSON = response.result.value {
                            print("JSON: \(JSON)")
                        }

                    }
                case .failure(let encodingError):

                    print(encodingError)
                    break
                }}}}

Hope somebody can help...Thanks...:)

  • why use two times loop? – Asaduzzaman Shuvro Oct 10 '17 at 07:55
  • Somewhere there is a (inner/hidden) call to `dataUsingEncoding:` which doesn't work because the object is a `(NS)Number` but not a `(NS)Data`. I'd say it's that line: `multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)`. You can't do `((value as AnyObject).data(using: String.Encoding.utf8.rawValue)` on any kind of class of `value`. I don't know what are the class of the other objects, but `"sequence": i,` should crash it. – Larme Oct 10 '17 at 07:55
  • I also tried giving the sequence a hardcoded value of "1" but then again it crashes maybe it is not accepting the image in the given format...The imageData is just shown as '403829 bytes'...could this be an issue, @Larme ? –  Oct 10 '17 at 07:59
  • the loop is used twice, @AsaduzzamanShuvro because sequence has the number of images taken from the gallery and the other loop iterates through each of the images picked... –  Oct 10 '17 at 08:01
  • use my answer https://stackoverflow.com/questions/45651187/upload-photo-file-with-json-and-custom-headers-via-swift-3-and-alamofire-4-i/46116478#46116478 just pass image like dict.set(imgview.image, forKey:"upload1") and if you are not uploading video then pass nil as parameter @User.bw – Jitendra Modi Oct 10 '17 at 08:58
  • In your answer, @JitendraModi what is webservice in self.webservice...? –  Oct 10 '17 at 09:03
  • it is object of this class WebServiceHandler. just declare like as let webservice = WebServiceHandler() – Jitendra Modi Oct 10 '17 at 09:05
  • Ok..I'll see... –  Oct 10 '17 at 09:10
  • was trying your code @JitendraModi..but a bit confused as to how I can use my parameters in your code...can you just help with that maybe....? –  Oct 10 '17 at 09:20

1 Answers1

0

Try to use this code.It's working for me.

let para: [String: Any]

Alamofire.upload(multipartFormData: {(multipartFormData) in

for i in 0..<uploadImages.count{         multipartFormData.append(UIImageJPEGRepresentation(uploadImages[i], 0.3)!, withName: "image\(i)", fileName: "swift_file\(i).jpeg", mimeType: "image/jpg")             
        }

        for (key, value ) in para {
            multipartFormData.append((value).data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: apiURL)
    { (result) in
        switch result {
        case .success(let upload, _,_ ):

            upload.uploadProgress(closure: { (progress) in
                UILabel().text = "\((progress.fractionCompleted * 100)) %"
                print (progress.fractionCompleted * 100)
            })


            upload.responseJSON { response in

                guard ((response.result.value) != nil) else{
            print(response.result.error!.localizedDescription)
                    return
                }
OMEESH SHARMA
  • 141
  • 1
  • 8