Alamofire session configurations are not reflected in the request - swift

Alamofire Version: 5.1
We are modifying our alamofire session configuration as following:
let apiManager: Session = {
let configuration = URLSessionConfiguration.af.default
configuration.timeoutIntervalForRequest = 20
configuration.requestCachePolicy = .reloadIgnoringCacheData
configuration.urlCache = nil
let manager = Alamofire.Session(
configuration: configuration,
cachedResponseHandler: ResponseCacher(behavior: .doNotCache)
)
return manager
}()
And we are making the request as following
apiManager.request(
url,
method: .post,
parameters: requestBodyParameters,
encoding: JSONEncoding.default,
headers: generateHeaders(enableAuth: authorisation) // to generate headers
)
.validate(statusCode: 200..<300)
.responseJSON { response in
print(response)
}
}
}
But the request configurations is not updated, they remain at default values
[Timeout]
60
[Cache policy]
UseProtocolCachePolicy

You're looking at the URLRequest generated by Alamofire which doesn't include the URLSession-level configuration, and which will never reflect the cache customization. If you want to see the actual URLRequest being performed after it passes through both Alamofire and URLSession, you can access the latest URLSessionTask that the Alamofire Request (in this case a DataRequest) performed by using request.task. However, like I said, this will never reflect the other behaviors you've attached, like a ResponseCacher, since those exist outside of the request pipeline.

Related

How to get original requests in Alamofire 5?

I made a wrapper for Alamofire which makes the data request first and then it prints the details of original URLRequest.
let dataRequest = session.request(url, method: .get, parameters: parameters)
let originalRequest = dataRequest.request
// Now print somehow the details of original request.
It worked fine on Alamofire 4.9, but it stopped in the newest 5.0 version. The problem is that dataRequest.request is nil. Why this behavior has changed? How can I access URLRequest underneath DataRequest?
URLRequests are now created asynchronously in Alamofire 5, so you're not going to be able to access the value immediately. Depending on what you're doing with the URLRequest there may be other solutions. For logging we recommend using the new EventMonitor protocol. You can read our documentation to see more, but adding a simple logger is straightforward:
final class Logger: EventMonitor {
let queue = DispatchQueue(label: ...)
// Event called when any type of Request is resumed.
func requestDidResume(_ request: Request) {
print("Resuming: \(request)")
}
// Event called whenever a DataRequest has parsed a response.
func request<Value>(_ request: DataRequest, didParseResponse response: DataResponse<Value, AFError>) {
debugPrint("Finished: \(response)")
}
}
let logger = Logger()
let session = Session(eventMonitors: [logger])
I had to obtain the URLRequest in a test case. Solved it by adding .responseData and using XCTestExpectation to wait for the async code to return:
func testThatHeadersContainContentEncoding() {
let exp = expectation(description: "\(#function)\(#line)")
let request = AF.request("http://test.org",
method: .post, parameters: ["test":"parameter"],
encoding: GZIPEncoding.default,
headers: ["Other":"Header"])
request.responseData { data in
let myHeader = request.request?.value(forHTTPHeaderField: additionalHeader.dictionary.keys.first!)
// .. do my tests
exp.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}

Multiple Arguments in AlamoFire.Request

I am trying to access Spotify's web API. I am currently using Alamofire to request the search operation which only requires a token. However, I could not figure out why it won't let me send multiple arguments.
let headers = ["Authorization": "Bearer {your access token}"]
var searchURL = "https://api.spotify.com/v1/search?q=Odesza&type=track"
AF.request(.GET, url, headers: headers)
.responseJSON { response in
debugPrint(response)
}
Alamofire does a great job of formatting parameters to a request url. Just as you pass parameters with the .post method to the AF request function you also pass a parameters [string : any] to the AF request for .get methods as well. The difference is .post will put the parameters in the request.body/data vs. .get will format the parameters into the url with the ?q=my_search_string
something along the lines of this:
Let params: [string :any] = ["q": "odesza", "type":"track"]
AF.request(.GET, url, parameters:params, headers: headers) .responseJSON { response in debugPrint(response

Alamofire 4 sends method as POST but server reads it GET

I have a very weird problem here, using Alamofire 4 Swift 4 Xcode 9.1
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 30
manager.session.configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let request = manager.request(
url,
method: HTTPMethod.post,
parameters: [:])
But server replies with method not allowed because it reads it as GET, however, if I change HTTPMethod.put or .delete or any other method, the server reads it correctly, the problem is with post specifically!
By debugging Alamofire's class 'SessionManager', specially the following method:
open func request(
_ url: URLConvertible,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = URLEncoding.default,
headers: HTTPHeaders? = nil)
-> DataRequest
The method here is correct, POST, so it's just fine before it goes out the application, what's wrong?
It was adding '/' at the end of the URL that was causing this.

Alamofire timeout url

I am using the Alamofire Swift library
Alamofire.request
(RestApiManager.sharedInstance.baseURL+"login?language="+lang,
method: .post,
parameters: requestDictionary,
encoding: URLEncoding.httpBody,
headers: headers
).responseObject(keyPath: "") { (response: DataResponse<User>) in
let user = response.result.value
print(user?.status)
print(user?.message)
}
So simply, I want to put a timeout of 60 seconds on every call I make.And i like to give a message connection timeout after 60 seconds. I also want to know, if there exists an internet connection or not. If it doesnt exist, I like to avoid calling alamofire.
Here's the Swift 3.0 / Alamofire 4.0 code to get an alamofireManager that has a 60 second timeout.
You need create a global variable for the request manager:
var alamoFireManager = Alamofire.Manager.sharedInstance
And after configure the custom parameters:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 60 // seconds
configuration.timeoutIntervalForResource = 60
self.alamoFireManager = Alamofire.Manager(configuration: configuration)

Alamofire POST Returning Data

I am using Alamofire to make a post request to server. The post request is working fine.
Issue: When the post request is made, it returns some data which I need. How can I store/ retrieve that data
The POST Request:
Alamofire.request(.POST, postURL, parameters: params)
to get the response closure add
.response { request, response, data, error in }
to the end of your code
ie
Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
If you are using the latest version of AlamoFire.
If you are using the latest version of AlamoFire.
Try this working fine for me.(Change request arguments based on your need)
let url1 = "http://yoururl.com"
let head = [ "Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json;charset=UTF-8"] // Adding headers
let p = ["Email":"anything","Password": "123"] // Adding parameters if any
Alamofire.request(.POST,url1, parameters: p, encoding : .JSON, headers : head)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
}