los.adrian
los.adrian

Reputation: 538

How could I check in Alamofire my request is sent?

With Alamofire is possible to get an event when request is sent whatever response is received or not? Just like with this URLSession method:

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
                            didSendBodyData:(int64_t)bytesSent
                             totalBytesSent:(int64_t)totalBytesSent
                   totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;

Edit: My code is send a JSON to the server:

Alamofire.request("http://...", method: HTTPMethod.post, parameters: params, encoding: JSONEncoding.default,
                      headers: [...]).responseJSON {
                                    response in
                                    if response.result.isSuccess {
                                        print("result is Success")
                                    } else {
                                        print("result is Failure")
                                    }
    }

I want to handle what if the network is disconnected and I'd like to know that response is arrived, or not.

Thank you in advance for any help you can provide.

Upvotes: 0

Views: 1540

Answers (2)

Enea Dume
Enea Dume

Reputation: 3232

Response Validation

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

Manual Validation

Alamofire.request("https://httpbin.org/get")
    .validate(statusCode: 200..<300)
    .validate(contentType: ["application/json"])
    .responseData { response in
        switch response.result {
        case .success:
            print("Validation Successful")
        case .failure(let error):
            print(error)
        }
    }

Automatic Validation

Automatically validates status code within 200..<300 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
    switch response.result {
    case .success:
        print("Validation Successful")
    case .failure(let error):
        print(error)
    }
}

Statistical Metrics

Timeline Alamofire collects timings throughout the lifecycle of a Request and creates a Timeline object exposed as a property on all response types.

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.timeline)
}

The above reports the following Timeline info:

  • Latency: 0.428 seconds
  • Request Duration: 0.428 seconds
  • Serialization Duration: 0.001 seconds
  • Total Duration: 0.429 seconds

Taken from Alamofire Usage. U can have e deeper look.

Upvotes: 3

Scriptable
Scriptable

Reputation: 19750

You can just use the standard closure which will give you a response. This closure would be called whether the response is an error or not. If you want to check the progress of an upload it can also do that

Alamofire.download("https://httpbin.org/image/png")
    .downloadProgress { progress in // progress
        print("Download Progress: \(progress.fractionCompleted)")
    }
    .responseData { response in // usual place to get response
        if let data = response.result.value {
            let image = UIImage(data: data)
        }
    }

Have a read of the Making a request documentation for more information

Upvotes: 1

Related Questions