how tobuild url request with get method using alamofire - ios

I am not aware of building api with dynamic values.I have an api and from that, i want to get pluscode by sending url request with latitude, longitude and email to base url.My requirement is sending request in get method with lat,long and email values and getting pluscode from response.Can anyone help me to build this url.
lat = locValue.latitude
long = locValue.longitude
email = abcdefg#gmail.com
//base url
var pluscodeurl = "https://plus.codes/api?address="
let postParameters = ["address":lat+long ,"email":"mahithaa.angadi#gmail.com"] as [String : Any]
Alamofire.request(pluscodeurl, method: .get, encoding: URLEncoding.default, headers: nil).responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(_):
break
}
}

Here is the snippet you can write it
let lat = "19.0760"
let long = "72.8777"
let email = "abc#test.com"
let ApiURL = "https://plus.codes/api?address=\(lat),\(long)&email=\(email)"
Alamofire.request(ApiURL).responseJSON { response in
print("Result: \(response.result)")
if let json = response.result.value {
print("JSON: \(json)")
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}
}

You can write your url in the below format:
let email = "abc#gmail.com"
let pluscodeurl = "https://plus.codes/api?address=\(lat),\(long)&email=\(email)"

Related

How to send request in Alamofire 4.0 only with parameters and Body using POST method in swift?

I am using like this, but in this case, I need to call API with parameters and Body. Please help me. Thanks in advance.
Alamofire.request(postUrl, method: .post, parameters: params, encoding: CustomPostEncoding(), headers: nil).validate().responseJSON{ response in
switch response.result
{
case .success:
MBProgressHUD.hide(for: self.view, animated: true)
if let val = response.result.value
{
let json = JSON(val)
print(json)
}
case .failure(let error):
print(error)
}
}
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
Refrence :- POST request with a simple string in body with Alamofire
use your parameters instead of class_id ,and time.
func listOfClassesData(url: String,class_id: String,time: String,redClassesData : [String: Any] ,completionHandler:#escaping (Bool) -> ()){
let Auth_header = ["Authorization" : "Bearer "+getBearerToken()]
let paameters:Parameters = [
"class_id" : class_id,
"time" :time,
]
print(url,Auth_header)
Alamofire.request(url, method: .post, parameters: paameters, encoding: JSONEncoding.default, headers: Auth_header)
.responseJSON { response in
print(response)
switch response.result{
case .success:
let statusCode: Int = (response.response?.statusCode)!
switch statusCode{
case 200:
if let json = response.result.value{
completionHandler(true)
}
break
default:
completionHandler(false)
break
}
break
case .failure:
completionHandler(false)
break
}
}
}
let url = "your api url"
let param = ["user":"user#test.com","pass":"12345"]
Alamofire.request(url, method: .post , parameters: param)
.validate()
.responseJSON {
response in
switch response.result{
case .success:
var jsonResult = [String:AnyObject]()
do
{
//Get response successfully of api
jsonResult = try JSONSerialization.jsonObject(with: response.data!, options: []) as! [String:AnyObject]
print(jsonResult)
}
catch let error as NSError {
//get error if there is any problem in response of api.
print("--->",error)
}
case .failure(let error):
//get error if there is any problem while calling api.
print("---->",error)
}
}

Replicating post method in Postman with parameters and body-raw into Alamofire

I'm having a problem on using Alamofire. When I try to post a request using a generic parameters like ["name":"John", "age":"27"] it always succeeds. But, when I try to use a web service that requires parameters and a body-raw for a base64 string I'm not able to get a successful response from the server. Though it succeeds when I use Postman. Does anyone knows how to do this on Alamofire 4? Here is the screenshot of my postman.
Thank you!
#nathan- this is the code that I used. I just assumed that the base64String inside the "let paramsDict" has a key value named "data" though it doesn't have a key name in postman.
let urlString = ApiManager.sharedInstance.formsURL + ApiManager.sharedInstance.mobileFormsImageUpload
let paramsDict = ["token": token, "fileID":"2", "filename":"images.png", "data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: URLEncoding.httpBody, headers: [:])
.responseJSON{ response in
switch response.result {
case .success(let data):
debugPrint("SUCCESS")
case .failure(let error):
debugPrint("Request Error")
}
}
I already figured it out. It needs a custom encoding to make it work. All the parameters must be inlined with the url so the base64 string inside the parameter is the only to be encoded. Here is the code that I used.
struct CustomPostEncoding: ParameterEncoding {
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try URLEncoding().encode(urlRequest, with: parameters)
let base64 = parameters?["data"] as! String
let finalBase64Format = "\"" + base64 + "\""
let postData = NSData(data: finalBase64Format.data(using: String.Encoding.utf8)!)
request.httpBody = postData as Data
return request
}
}
func uploadImageBase64(){
let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(testIMG, jpegCompressionQuality)?.base64EncodedString() {
var token = String()
if let data = UserDefaults.standard.data(forKey: "userProfile"),
let user = NSKeyedUnarchiver.unarchiveObject(with: data) as? UserProfile{
token = user.token
} else {
print("There is an issue")
}
let headers = [
"content-Type": "application/json"
]
let urlString = "http://localhost/FormsService.svc/Getbase64?filename=test.png&fileID=1151&token=80977580xxx"
let paramsDict = ["data": base64String] as [String : Any]
Alamofire.request(urlString, method: .post, parameters: paramsDict, encoding: CustomPostEncoding(), headers: headers)
.responseJSON{ response in
print("response JSON \(response.result)")
}
.response{ response in
print("RESPONSE \(response)")
}
}
}

Post method request Alamofire

I'm using Swift 3 and Alamofire 4.0.
I want to create similar Alamofire POST request as Postman request shown in screenshot:
I've tried with these lines of code:
var parameters: [String: Any] = [
"client_id" : "xxxxxx",
"client_secret" : "xxxxx",
"device_token" : "xxxx",
"fullname" : "xxxxx",
"gender": "xxx"
]
Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
print(response)
}
But I got this error:
How to implement POST request with Body as form-data using Alamofire in Swift 3?
Swift 3.0 - Alamofire - Working code for multipart form data upload *
// Parameters
let params: [String : String] =
["UserId" : "\(userID)",
"FirstName" : firstNameTF.text!,
"LastName" : lastNameTF.text!,
"Email" : emailTF.text!
]
// And upload
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in params
{
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
upload.uploadProgress(queue: DispatchQueue(label: "uploadQueue"), closure: { (progress) in
})
case .failure(let encodingError):
print(encodingError)
}
}
)
Let me know if you still have issues with it.
after too much try I have succeded so try this
override func viewDidLoad() {
super.viewDidLoad()
let parameters: Parameters = ["client_id": "1","user_token":"xxxxxxxx"]
// Do any additional setup after loading the view, typically from a nib.
let url = "http://xxxxxxxxxxx/index.php/Web_api/get_client_profile"
//let timeParameter = self.getLastTimeStamp()
self.request = Alamofire.request(url, method: .post, parameters:parameters)
if let request = request as? DataRequest {
request.responseString { response in
//PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
print(dictionary)
}catch{
}
}
}
}
var request: Alamofire.Request? {
didSet {
//oldValue?.cancel()
}
}
You can post a request using Alamofire.
let url = ""
let headers = [ "Content-Type" : "application/json"]
let para : Parameters = [ "data" : JSONObject]
Alamofire.request(url, method: .post, parameters: para, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Nothing to worry about.
Alamofire request method not changed so much(For Swift 3.0) if in case you know how to do that in Swift 2.0/2.2. If you understand the old method then you can easily understand this one also. Now lets take a closer look on the following boilerplate -
Alamofire.request(apiToHit, method: .post, parameters: parametersObject, encoding: JSONEncoding.default, headers: headerForApi).responseJSON { response in switch response.result{
case .success(_):
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
//Got the status code and data. Do your data pursing task from here.
}
}else{
//Response data is not valid, So do some other calculations here
}
case .failure(_):
//Api request process failed. Check for errors here.
}
Now here in my case -
apiToHit //Your api url string
.post //Method of the request. You can change this method as per you need like .post, .get, .put, .delete etc.
parametersObject // Parameters needed for this particular api. Same in case you are sending the "body" on postman etc. Remember this parameters should be in form of [String: Any]. If you don't need this then you can just pass nil.
JSONEncoding.default //This the encoding process. In my case I am setting this as .default which is expected here. You can change this to .prettyPrinted also if you need.
headerForApi //This is the header which you want to send while you are requesting the api. In my case it is in [String: String] format. If you don't need this then you can just pass nil.
.responseJSON //Expecting the response as in JSON format. You can also change this as you need.
Now, in my request I am using Switch inside the request closure to check the result like response in switch response.result{.
Inside case .success(_): case I am also checking for result data and http status code as well like this
if let receivedData: Any = response.result.value{
if let statusCode: Int = response.response?.statusCode {
}
}
Hope this helped. Thanks.
class func alamofireMethod(methods: Alamofire.HTTPMethod , url : URLConvertible , parameters : [String : Any],need_flag_inside : Bool = false, paramJson : Bool = true ,need_loader : Bool = true,Header: [String: String],handler:#escaping CompletionHandler,errorhandler : #escaping ErrorHandler)
{
if NetworkController.sharedInstance.checkNetworkStatus()
{
var alamofireManager : Alamofire.SessionManager?
var hed = Header
if let tok = UserDefaults.standard.value(forKey: "TOKEN") as? String {
hed = ["Authorization":"Bearer \(tok)"]
}
if need_loader {
// DELEGATE.showLoader()
}
var UrlFinal = ""
do
{
try UrlFinal = baseURL + url.asURL().absoluteString
}
catch{}
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = 25
configuration.timeoutIntervalForRequest = 25
configuration.httpAdditionalHeaders = hed
alamofireManager = Alamofire.SessionManager(configuration: configuration)
alamofireManager = Alamofire.SessionManager.default
let json = JSON(parameters)
guard let jsonDict = json.dictionaryObject else {
return
}
var jsonData = Data()
do {
jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: [])
} catch {
//handle error
print(error)
}
var request = URLRequest(url: URL(string: UrlFinal)!)
request.httpMethod = methods.rawValue
if methods == .post || methods == .put
{
//check here
if paramJson {
hed["Content-Type"] = "application/json"
request.httpBody = jsonData
}else{
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
}
}
request.allHTTPHeaderFields = hed
Alamofire.request(request).responseJSON(queue: nil, options: JSONSerialization.ReadingOptions.allowFragments) { (response) in
print(parameters)
print(UrlFinal)
print(hed)
// DELEGATE.hideLoader()
if response.result.isSuccess
{
print(response)
handler(response.result.value! as AnyObject)
}
else if response.response?.statusCode == 401
{
// DELEGATE.redirectToLogin()
// DELEGATE.showToast(message: "Token Expired")
}
else{
// DELEGATE.showToast(message: default_failure)
errorhandler(response.result.error! as NSError)
print(response.result.error as Any)
}
}
}else{
// DELEGATE.showToast(message: "Please check your internet connection.")
}
}
Alomofire With Post and Put Method In swift

Alamofire Parameter missing in response

I install pod file of Alamofire for calling web service and successfully retrieve data when there is no parameter pass to web service but when I try to pass parameter It shows this parameter missing.
Here is my code:
let parameters: Parameters = ["client_id": "1","user_token":"A4YkkH5FdTbRCI8Mk98s"]
let url = "http://***********/index.php/Web_api/get_client_profile"
Alamofire.request(url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
print(response.result.value)
}
break
case .failure(_):
print(response.result.error)
break
}
}
RESPONSE:
{
"message : client_id parameter missing",
"Code : 500"
}
What I am doing wrong ? Please help me with it.
Thank you
After banging my head for like 6 Hours I figured a different approach, here is a way of calling it, which works:
var request: Alamofire.Request? {
didSet {
oldValue?.cancel()
}
}
func loadDataFromServer(message:String?) {
// Prerequisites for Connection to Server
let timeParameter = self.getLastTimeStamp()
let url = "http://your.amazing.url/path/component/classs"
let parameter = ["timestamp":timeParameter]
//sho hud only of there is no data listed
if message != nil {
HUD.show(HUDContentType.label("Loading.."))
}
self.request = Alamofire.request(url, method: .post, parameters:parameter)
if let request = request as? DataRequest {
request.responseString { response in
PKHUD.sharedHUD.hide()
do{
let dictionary = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
//Save and Fetch
self.saveTimestamp(dictionary: dictionary, wsEntity: "Section")
self.saveDataInPersisanceStorage(articalDictionary: dictionary)
self.fetchDatafromCore()
//HUD.flash(.success, delay:1.0)
}catch{
//HUD.flash(.error, delay:1.0)
}
}
}
}

Alamofire 4 and special characters in JSON

I've got a problem with special characters with Alamofire 4.The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.Alamofire 4 shows something like this instead:
U00e6
Using this call:
Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in
print(response)
}
What to do to solve this?
Edit:
Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let value) :
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value as! [String:AnyObject]!{
print("JSON: ",JSON)
self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!
self.tableView.reloadData()
}
case .failure(let encodingError):
//Print error
}
}
I got the issue that I have added æ in json response and try to print.
Output:
JSON: Optional(<__NSArrayI 0x600000050320>(
{
"email_address" = "testwts06#gmail.com";
username = "testwts06 \U00e6";
},
{
"email_address" = "testwts01#gmail.com";
username = "testwts01 \U00eb";
},
{
"email_address" = "testwts100#gmail.com";
username = testwts100;
})
While displaying it display in correct format.
Swift 3 update for Ekta's answer:
let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.
JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.
You could try to convert the response data to correct UTF8 encoding:
let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue)
let data = datastring!.data(using: String.Encoding.utf8.rawValue)
do {
let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
let jsonDic = object as! NSDictionary
print(" ok, successfully converted..\(jsonDic)")
} catch let aError as Error {
// print and handle aError
}
Hope it helps you.
Here is a simple String extension that solves the issue:
extension String {
func fixUnicode() -> String {
var copy = self as NSString
let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)
let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()
matches.forEach {
let char = copy.substring(with: $0.rangeAt(1))
copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString
}
return copy as String
}
}

Resources