How to read the body of a POST request with GCDWebServer in Swift

2k Views Asked by At

I'm trying to use GCDWebServer to read/write to a file in the documents directory. Reading the file seems fairly straight-forward and I've pretty much got that how I need.

I want to write to the file using a POST request. So I tried adding a handler for method "POST", but in the process block I can't seem to read the body of the request at all.

If I do something like:

webServer?.addHandler(forMethod: "POST", path: "/post", request: GCDWebServerDataRequest.self, processBlock: {request in

        dump(request)

        return GCDWebServerDataResponse(html: "An error occurred.")
    })

That prints all the headers to the console (in an NSObject). But how do I read in the body to a variable?

(iOS 10.3, Swift 3, XCode 8.3.2)

1

There are 1 best solutions below

0
On
    self.webServer?.addHandler(forMethod: "POST", path: "/uploadfile", request: GCDWebServerMultiPartFormRequest.classForCoder(), processBlock: { (request) -> GCDWebServerResponse? in

        print("ádasdnaskdnaskjd=====<")
        let get = request as! GCDWebServerMultiPartFormRequest

        do {

            if let files = get.files {

               try files.forEach({ (file) in

                    if let multipartFile = file as? GCDWebServerMultiPartFile {

                        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                        let urlOfFile = documentsPath.appending("/\(multipartFile.fileName!)");
                        let url = URL(fileURLWithPath: urlOfFile)

                        let fileManager = FileManager.default
                        try fileManager.moveItem(at: URL(fileURLWithPath: multipartFile.temporaryPath), to: url);

                        print("URL of file: \(url)")
                    }

                })

            }

            return GCDWebServerDataResponse.init(html: "")

        } catch {
            print(error.localizedDescription)
        }

        return GCDWebServerDataResponse.init(html: "")

    })

You can use postman to test it with body (form-data)