1

I'm new to swift and I'm doing my best to learn fast. right now I'm struggling with multipart form data.i have an API which has a ticket system, it takes 2 String and one Integer and One fileData(Picture). the server admin says I have to use a multipart form data to have a successful POST request.

The API

I'll be thankful if anybody could help me with the code. the API Address is: http://app.avatejaratsaba1.com/api/Ticket/SendTicket it works fine in postman but when I try the postman code for swift , I get some errors?!

UPDATE:

let headers = [
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
            "Cache-Control": "no-cache",
            "Postman-Token": "ed42f6a7-a01c-432f-82f4-bed9560814e1"
        ]
        let parameters = [
            [
                "name": "Title",
                "value": "abcd3"
            ],
            [
                "name": "Description",
                "value": "a"
            ],
            [
                "name": "Unit",
                "value": "1"
            ],
            [
                "name": "FileData",
                "fileName": "/Users/Am1rFT/Desktop/Screen Shot 2018-07-06 at 1.14.03 AM.jpg"
            ]
        ]

        let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"

        var body = ""
        var error: NSError? = nil
        for param in parameters {
            let paramName = param["name"]!
            body += "--\(boundary)\r\n"
            body += "Content-Disposition:form-data; name=\"\(paramName)\""
            if let filename = param["fileName"] {
                let contentType = param["content-type"]!
                let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
                if (error != nil) {
                    print(error)
                }
                body += "; filename=\"\(filename)\"\r\n"
                body += "Content-Type: \(contentType)\r\n\r\n"
                body += fileContent
            } else if let paramValue = param["value"] {
                body += "\r\n\r\n\(paramValue)"
            }
        }

        let request = NSMutableURLRequest(url: NSURL(string: "http://app.avatejaratsaba1.com/api/Ticket/SendTicket")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData as Data

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error)
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse)
            }
        })

        dataTask.resume()

The Errors

Update

Error

UPDATE:

if let filename = param["fileName"] {
            let contentType = param["content-type"]
            do{
                let fileContent = try  String(contentsOfFile: filename as! String , encoding: String.Encoding.utf8)

            if (error != nil) {
                print(error as Any)
            }

in this part of the code i get

" Thread 1: signal SIGABRT "

and in the console it shows :

" Could not cast value of type 'UIImage' (0x1b4c9ad50) to 'NSString' (0x1b4c767b8)."

Am1rFT
  • 227
  • 5
  • 18
  • Add your code and the error. – Sharad Chauhan Jul 11 '18 at 05:05
  • I just added the code and a picture to show the errors! – Am1rFT Jul 11 '18 at 05:08
  • just to clarify all the data( 2 String , one Integer and one picture) will be taken from user – Am1rFT Jul 11 '18 at 05:09
  • as you can see there is a postData which has never declared in the code , I don't know what Postman is doing exactly – Am1rFT Jul 11 '18 at 05:12
  • in this reference you sent where should i define that there are 3 more data to be sent? – Am1rFT Jul 11 '18 at 05:18
  • 3
    Refer this one: https://stackoverflow.com/a/26163136/6059313 . – Sharad Chauhan Jul 11 '18 at 05:24
  • You don't use exact Postman code for Swift, those headers are mostly for Postman to use for themselves. Also, if you are new then just use Alamofire, your code is probably never gonna work as it have way too many errors, you even use some `filename` for a place that is suppose to be image data – Tj3n Jul 11 '18 at 05:28
  • Use `Moya` abstraction layer – SPatel Jul 11 '18 at 05:31
  • @SharadChauhan "Use of unresolved identifier 'generateBoundaryString' " in the last reference – Am1rFT Jul 11 '18 at 05:55
  • @ItanHant You have to take only what is needed for you. For ex generateBoundaryString is a function if you search this on that answer's page you will see what that function returns. – Sharad Chauhan Jul 11 '18 at 05:57
  • i just added an image which show an error, i dont't know why that returns nil – Am1rFT Jul 11 '18 at 07:17
  • There are many issues. The most significant is that you can't get image data from an URL with `String(contentsOfFile` because the file doesn't contain a string. You have to get the image data with `Data` API and base64-encode it. The first error in the screenshot means what it says: You have to use `try` and the `do - catch` error handling (affects also the `Data` API). The `NSError` instance is unused. The second error is very clear, too: The variable is not defined. You can simply write `request.httpBody = Data(body.utf8)`. And this is Swift: No `NSMutable...` types, use native types. – vadian Jul 11 '18 at 07:28
  • @vadian i'm not getting image from API , I'm sending the Image to the Api! do you know what should i do? – Am1rFT Jul 11 '18 at 07:38
  • @vadian i just added part of the code which returns a error – Am1rFT Jul 11 '18 at 08:42
  • Once again, the file contains an image as raw `Data` not `String`, you have to use `Data(contentsOf` and encode the data with base64Encoding. – vadian Jul 11 '18 at 08:43
  • @vadian i fixed the first part but the encoding part anywhere i try to add base64 encoding it shows errors? – Am1rFT Jul 11 '18 at 08:56
  • @vadian just to clarify again, i'm sending the image from my ios to the API – Am1rFT Jul 11 '18 at 09:05

0 Answers0