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.
Related
I have three different data fetching methods like the following sample. Three different methods should return different decodable types. The only difference between these methods is the Type that they would be parsed into. Obviously three different methods is just code duplication.
It works that way but I want to simplify and refactor that methods. I have three different response types. I guess I need to use switch case with some enum or use enums as parameters. But I don't know how to do that.
func fetchProducts(with parameters: CategoryParams, completion: #escaping (ProductsResponse) -> Void) {
AF.request(productURL, method: .get, parameters: parameters, headers: headers).responseDecodable(of: ProductsResponse.self) { res in
switch res.result {
case .success:
DispatchQueue.main.async {
completion(res.value!)
}
case .failure(let error):
print(error)
}
}
}
Generic! you should input the specific type that you want to decode.
func fetchProducts<RespType>(with parameters: CategoryParams, respType: RespType.Type, completion: #escaping (RespType) -> Void) {
AF.request(productURL, method: .get, parameters: parameters, headers: headers).responseDecodable(of: RespType.self) { res in
switch res.result {
case .success:
DispatchQueue.main.async {
completion(res.value!)
}
case .failure(let error):
print(error)
}
}
}
I am slowly distributing my app to Beta testers via TestFlight.
A few of them have already reported that the app showed “No Internet connection” while on WiFi. As soon as they switched to cellular everything started to work. The WiFi works for everything else.
I use Alamofire as a framework to make HTTPRequests and when these requests fail, “No Internet connection” error is displayed.
My backend service is hosted on Google Cloud
My domain is registered using AWS Route 53
I use SSL certificates managed by Google
All HTTPRequests are sent to https://api.myapp.com (where myapp.com is hosted on AWS).
All of the testers have Automatic DNS resolution set in Settings -> WiFi -> (i) -> DNS
Any ideas what the cause can be or how I can further investigate this issue?
This is the piece of code used to make GET requests:
func getJSON(_ url: String,
parameters: [String: String] = [:],
headers: [String: String] = [:],
completionHandler: #escaping (_ result: JSON?,
_ headers: [String: String]?,
_ statusCode: Int?,
_ error: Error?) -> Void) {
Self.sessionManager.request(
url,
method: .get,
parameters: parameters,
headers: self.createHeaders(headers: headers),
interceptor: self,
requestModifier: { $0.timeoutInterval = HttpClient.defaultTimeoutInterval }
).validate().responseJSON { response in
switch response.result {
case .success(let data):
let json = JSON(data)
completionHandler(json, self.getResponseHeaders(httpUrlResponse: response.response), response.response?.statusCode, nil)
case .failure(let error):
completionHandler(nil, self.getResponseHeaders(httpUrlResponse: response.response), response.response?.statusCode, error)
}
}
}
The connection error is displayed when error != nil. When it happens, it happens for all HTTP endpoints (does not matter if an endpoint requires authentication or authorization, all HTTP requests fail).
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'm developing an iOS app in Swift 3 (I'm a complete Swift n00b.) I am authenticating against an external app, to get an access token back, but the code is not redirecting back to my app after authenticating against the external app.
AppDelegate.swift
func application(_ application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: Any) -> Bool {
print(url)
DispatchQueue.main.async {
print(url.scheme)
if (url.scheme == "myapp"){
print("i just caught a url and i feel fine and the url be says ", url)
}
}
return true
}
in class that handles response from external app:
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
if((response.result.value) != nil) {
let swiftyJsonVar = JSON(response.result.value!)
if let resData = swiftyJsonVar[key].string {
let autostart_data = swiftyJsonVar[key].string
... snip ...
let url = URL(string: "extapp:///?key=\(data!)&redirect=\(myapp)://key")
UIApplication.shared.open(url!, options: [:])
... snip ...
}
}
}
Is it possible to redirect back to my app, with Alamofire, once the response is received? I have been researching online with Google for the past two days and have tried out many possible solutions, but have come to nothing so far. I'd appreciate any help!
Problem is not with Alamofire. It's to do with the external app's API and my iOS app not being able to redirect back.
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>