I have the following Swift function in a protocol that represents a POST HTTP request:
func post<T: Mappable>(url: NSURL, parameters: [String: AnyObject]?, completion: ((Result<T, APIClientError>) -> ())?)
In this case, I'm doing import Result to get Result from Antitypical, because I don't want this protocol to depend on Alamofire.
In an implementation of this protocol, I want to use Alamofire to do the actual HTTP request:
func post<T: Mappable>(url: NSURL, parameters: [String: AnyObject]?, completion: (Result<T, APIClientError> -> ())? = nil) {
Alamofire.request(.POST, url.URLString, parameters: parameters, encoding: .JSON)
.validate()
The problem is that there is a conflict between Antitypical's Result and Alamofire's Result:
AlamofireHTTPClient.swift:21:87: 'Result' is ambiguous for type lookup in this context
How can I specify that I want to use Result from Antitypical? Or if you know a better way to solve the problem?
You can specify the exact type you are referring to by moduleName.Type; In your case that would be Result.Result or Alamofire.Result .
Swift 5
In Swift 5, you can specify the Swift result type as:
Swift.Result<T, APIClientError>
Alamofire can be done as:
Alamofire.Result<Data>
Related
I am doing an Alamofire request, and now I need to do a get request. In this request I should send query that is in Bool type(picture is in below link). This is my method to do request.
func setupRequest(path: Paths, method: RequestMethod, body: Encodable? = nil, params: [String: Any]? = nil, header: HeaderType, completion: #escaping((Result<Data,NetworkError>) -> Void)) {}
I am sending this arguments. How can I send the demanded query?
https://i.stack.imgur.com/ZgVZ6.png
I got this error many times in my project and it very irritates me because I have full internet connectivity though I get this error repeatedly.
What is the solution...?
I am using
Swift - 3.3
Alamofire - 4.7.3
API Calling Code:
class func post(_ URL: String, withParams params: [String : AnyObject], onView parentView: UIViewController, hnadler completion: #escaping ([AnyHashable: Any]!) -> Void) {
var URLString = String()
URLString = APIConstants.kServerURL + URL
var headers = [String: String]()
headers["Content-Type"] = "application/x-www-form-urlencoded"
Alamofire.request(URLString,method: .post, parameters: params , headers : headers)
.validate(contentType: ["application/vnd.api+json"])
.responseJSON { response in
switch response.result {
case .success( _):
var completionVarible = [NSObject : AnyObject]()
completionVarible = response.result.value as! [AnyHashable: Any]! as [NSObject : AnyObject]
completion(completionVarible)
case .failure(let error):
self.handleFailureResponse(Error: error as NSError?, parentView: parentView)
}
}
}
If the alert appears immediately you may try to change the cache policy to
.reloadIgnoringCacheData
I don't know exactly why this error occurs but I have also faced this error, so I have put one solution. This error has some unique error code. So check that error code and ignore alert over there or you can again try this API call if this error code you get.
I find one solution to this issue if you using Alamofire.
First import Alamofire in your common class otherwise you can create a separate class for check internet connection.
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Call below method before you API call
if !Connectivity.isConnectedToInternet() {
ServiceHandler.ShowAlert(message: "Check your internet connectivity.", title: "Error", parentView: self) //This is my comman method for display alert.
return
}
I am a beginner in swift iOS and I am doing login module of an application in iOS but I am stuck at one thing I have login api but when I am checking response in postman when I am sending parameters as "raw" than it is showing user logged in but when I am sending the same parameters as "form-data" than it is showing wrong id and password....can anyone tell me how to send parameters as "raw" so that I can get correct response?? Thanks for your help!!
Please try this method if you are using Alamofire library for API call.
func request(_ method: HTTPMethod
, _ URLString: String
, parameters: [String : AnyObject]? = [:]
, headers: [String : String]? = [:]
, onView: UIView?, vc: UIViewController, completion:#escaping (Any?) -> Void
, failure: #escaping (Error?) -> Void) {
Alamofire.request(URLString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
switch response.result {
case .success:
completion(response.result.value!)
case .failure(let error):
failure(error)
}
}
}
Also remember you need to pass Application/JSON header while calling this method.
["Content-Type": "application/json"]
From: http://toolsqa.com/postman/post-request-in-postman/
Check if your raw is using the correct format type as specified below.
I have these two methods in my API class to get data from an API:
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
makeAuthenticateUserCall(completionHandler)
}
func makeAuthenticateUserCall(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
Alamofire.request(.GET, loginUrlString)
.authenticate(user: "a", password: "b")
.responseString { request, response, responseString, responseError in
completionHandler(responseObject: responseString as String!, error: responseError)
}
}
Then in another class i use the following code to access the data:
API().authenticateUser{ (responseObject, error) in
println(responseObject)
}
The code is working but i don't understand it completely.
func authenticateUser has the parameter completionHandler: (responseObject: String?, error: NSError?) -> (), is this a reference to the completionHandler method? or is it an object? whats the purpose of -> ()?
When i call the authenticateUser func, how do i actually access the response? There is no return in any of my api funcs, the funcname{(parameter, parameter) in .. } syntax seems really strange.
completionHandler is a closure parameter. As Swift documentation says:
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
So, what a closure is used for is to add some functionality of your own that you want to add to the execution of your function.
In your case, you call authenticateUser and you pass a closure that receives (responseObject, error) and executes println(responseObject). authenticateUser() receives your closure under the completionHandler parameter and it then calls makeAuthenticateUserCall() passing your completionHandler closure to it.
Then again, looking at the definition you can see func makeAuthenticateUserCall(completionHandler: (responseObject: String?, error: NSError?) -> ()) that means that like authenticateUser() makeAuthenticateUserCall() is a function that receives a closure as a parameter, under the name of completionHandler. makeAuthenticateUserCall() makes a network request using AlamoFire and you capture the response under a closure again that you pass as parameter of the responseString() method. So you have:
//here you call authenticateUser with a closure that prints responseObject
API().authenticateUser{ (responseObject, error) in
println(responseObject)
}
Then:
//authenticateUser receives your closure as a parameter
func authenticateUser(completionHandler: (responseObject: String?, error: NSError?) -> ()) {
//it passes your closure to makeAuthenticateUserCall
makeAuthenticateUserCall(completionHandler)
}
//makeAuthenticateUserCall receives your closure
func makeAuthenticateUserCall(completionHandler: (responseObject: String?,
error: NSError?) -> ()) {
Alamofire.request(.GET, loginUrlString)
.authenticate(user: "a", password: "b")
//here you pass a new closure to the responseString method
.responseString { request, response, responseString, responseError in
//in this closure body you call your completionHandler closure with the
//parameters passed by responseString and your code gets executed
//(that in your case just prints the responseObject)
completionHandler(responseObject: responseString as String!, error: responseError)
}
}
For more information read the documentation: Swift Closures
I'm using Alamofire, with ObjectMapper, things were so smooth before upgrading to Swift 2.0, now,
For the following signature:
public func responseArray<T: Mappable>(completionHandler: ([T]?, ErrorType?) -> Void) -> Self
I'm calling
Alamofire.request(.GET, URL, parameters: nil)
.responseArray { (response: [MyObject]?, error: NSError?) in
}
and getting the following error:
Cannot invoke 'responseArray' with an argument list of type
(([MyObject]?, NSError?) -> ())
Any help will be super appreciated.
try this.
Alamofire.request(.GET, URL, parameters: nil)
.responseArray { (response: [MyObject]?, error) in
//your process
}