1

I'm doing a app which takes input from the user and generates PDF file.i"m trying to upload generated pdf file to api.but, i'm not getting how to do it, i'm totally new to swift.can anyone please give me a exsample on how to upload a file to api Thanks in advance

1 Answers1

0

First, I'd suggest you consider using Alamofire if you don't want to get lost in the idiosyncrasies of composing network requests. If you do it yourself, it can get pretty hairy (see https://stackoverflow.com/a/26163136/1271826 for example of how to construct multipart/formdata request manually).

Second, in terms of how that request should be formed, it depends entirely upon how you designed the API. But the easiest for file uploads is to support multipart/formdata requests (e.g. in PHP, using the $_FILES mechanism). See http://php.net/manual/en/features.file-upload.php. Or see example here that not only uploads image file (which you can easily modify to accept PDFs), but constructs JSON response, too: https://stackoverflow.com/a/19743872/1271826.

Anyway, if your server is designed to handle multipart/formdata requests, you can create request and parse the response using Alamofire, as shown in the Uploading MultipartFormData section of the README file:

Alamofire.upload(
    .POST,
    "https://httpbin.org/post",
    multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
        multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
    },
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    }
)
Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • Thanks! for your reply, i used Alamofire. when installed it in my project i got errors like expected expressions in the code of Alamofire . Actually i'm new to swift i don't know how to use Almofire or any third party libraries. –  Aug 06 '16 at 11:07