Search code examples
iosswiftnetwork-programmingalamofireshare-extension

API Request Fails immediately in iOS share extension


Hi I'm using a share extension to post some data to my server using API request (Alamofire), the problem is that the request fails immediately and I don't know how to make it work, I read on some articles that I must use URLSession to send the request in the background but I couldn't find any example to how to make it work with alamofire, here is my code in share extension ViewController:

override func didSelectPost() {

    MessageHTTPHelper.submitMessage(contains: contentText, completion: { (response) in
        self.showAlert(title: "Result", message: response.result.isSuccess ? "SUCCESS" : "FAILURE")
    })

}

The MessageHTTPHelper.submitMessage is a helper function that I defined and it works in the main app perfectly I don't care about the response, I just want to send the request without any callbacks, can you please give me an example of sending a request in iOS share extension?


Solution

  • After lots of search and tests and fails, finally, this solution worked for me!

    and here is my code in didSelectPost()

    let body: Parameters = [ "version": Configs.currentReleaseVersion, "content": cleanTextContent ]

    let request = HTTPHelper.makeHTTPRequest(route: "message",
                               headers: HTTPHelper.defaultAuthHTTPHeaders,
                               verb: .post,
                               body: body,
                               apiV1Included: true)
    let queue = DispatchQueue(label: "com.example.background", qos: .background, attributes: .concurrent)
    
    request.responseJSON(queue: queue, options: .allowFragments) { (response) in
        if response.result.isFailure {
            guard let message = response.error?.localizedDescription else {
                self.dismiss()
                return
            }
            self.showAlert(title: "Error", message: message)
        }
    }
    

    The HTTPHepler.makeHTTPRequest is just a helper method which creates an Alamofire DataRequest Instance with given parameters and returns it