Polyline in google map for IOS swift - ios

I have been working in google poly line functionality. I have initialised the URL and I have used alamofire request. Everything with the URL is working fine but I could not draw the line and it was stating like invalid URL.
I have attached the code which I have tried.
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(pickupcordinates)&destination=\(dropCoordinates)&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270"
Alamofire.request(urlString,method: .get, parameters: nil,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
invalidURL(url: "https://maps.googleapis.com/maps/api/directions/json?origin=13.03589205752495,80.25411217280107&destination=13.0277895999, 80.22673778239999&mode=driving&key=AIzaSyDJUX9uBiZivQGlAu1KTUC1kcmaiAnI270")
The above is my console response error
I want to draw a poly line from my source to destination.

I am using this way give it a try. May help you.
func drawPath(source: CLLocationCoordinate2D, destination: CLLocationCoordinate2D){
let orgin = "\(source.latitude),\(source.longitude)"
let destin = "\(destination.latitude),\(destination.longitude)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(orgin)&destination=\(destin)&mode=driving"
Alamofire.request(url).responseJSON { response in
switch response.result {
case .success:
let json = JSON(data: response.data!)
let routes = json["routes"].arrayValue
print(response)
break
case .failure(let error):
print(error)
}
}
}

Related

"'isSuccess' is inaccessible due to 'internal' protection level", AlamoFire not working like before

Im using alamoFire on swift but i came across this problem: "isSuccess' is inaccessible due to 'internal' protection level".
I have tried this and i have also tried this,
here is my code:
AF.request(jsonURL, method: .get, parameters: parameters).responseJSON { (response) in
if response.result.isSuccess { //problem is here
print("Got the info")
print(response)
let flowerJSON : JSON = JSON(response.result.value!)
let list = flowerJSON["..."]["..."]["..."].stringValue
print(list)
}
}
result is now of the built-in Result enum type, which means you can do pattern matching on it. Your code can be rewritten as:
AF.request("", method: .get, parameters: [:]).responseJSON { (response) in
if case .success(let value) = response.result {
print("Got the info")
print(response)
let flowerJSON : JSON = JSON(value)
...
}
}
Use a switch statement if you want the error case as well:
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}

Handling base64String as response in Swift

I am receiving a base64String for Image in response of an Api but
unable to get the result through Alamofire.request method (tried
with get as well as post).
Alamofire.request(ApiUrl, method: .get, parameters: [:] , encoding:JSONEncoding.default, headers:kAuthorizationHeader).responseString { (response) in
switch response.result {
case .success(let responseString):
if let imageData = Data(base64Encoded: responseString),
let image = UIImage(data: imageData) {
print("image")
}
case .failure(let error):
print("\(error.localizedDescription)")
}
}
It always returns a failure with 'requestTimeOut' in case of get
method and 'Invalid value around character 0' for post.
Is there any way through which we can get the base64String so that I can convert the same to UIImage? Please advise.
I went and created a view in my python project which responds a string in a url. So using alamofire.. you need to request string rather than responseJSON
Alamofire.request("http://127.0.0.1:8000/stringResponse/", method: .get).responseString { (response) in
switch response.result {
case .success(let responseString):
if let imageData = Data(base64Encoded: responseString),
let image = UIImage(data: imageData) {
print("image")
}
case .failure(let error):
print("\(error.localizedDescription)")
}
}

How to access alamofire response

I'm new to iOS and I have some Swift code in app that's supposed to switch cases depending on the error message that I receive from the server. The message is wrapped and I'm having trouble getting to it. Here's the code
func sendAlamofireRequest(submissionURL: URL, parameters: Parameters, chosenTracker: String) -> String {
var outputMessage = ""
Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() {
response in
switch response.result {
case .success:
print("Validation Successful...\(String(describing: response.value))")
print("response value: \(String(response.value!))")
switch response.value {
case "error_none"?:
outputMessage = "No matching Group Code. If you are having trouble, please go to \nhttps://app.phillyscientists.com"
break
case "error_tooManyIDs"?:
outputMessage = "Error, please contact developer."
break
case "error_noGroupIDReceived"?:
outputMessage = "Try Again."
break
default:
let JSONResponse : JSON = JSON.init(parseJSON: response.result.value!)
//uncomment this section for debugging
// print("=================<JSON RESP>=================");
// print(JSONResponse)
// print("=================</JSON RESP/>=================");
//
let teacherNameGot = self.parseJSONData(json: JSONResponse, trackerValuePassed: chosenTracker)
self.saveJSONDataToUserDefaults(teacher: teacherNameGot)
// outputMessage = "Logged In Successfully!"
break
}
case .failure(let error):
outputMessage = String(error.localizedDescription)
print(outputMessage)
}
}
return outputMessage
}
Here's the output from console:
Validation Successful...Optional("{\"Error\":\"error_none\"}")
response value: Optional("{\"Error\":\"error_none\"}")
How do I get to the value so that the switch case actually starts working?
Thanks!
you can use Alamofire method .responseJSON which will give you an http object that has several attributes like request and response. Take this code as an example:
Alamofire.request("https://your-service-url.com/api", method: .post, parameters: paremeters, encoding: JSONEncoding.default, headers: headers).responseJSON{ (data) in
guard let statusCode = data.response?.statusCode, statusCode == 200, let result = data.result.value as? [[String: Any]] else{
print("Error with HTTP status \(data.response?.statusCode ?? 0)")
return
}
var events : [Event] = []
result.forEach({ (rawEvent) in
events.append(Event(from: rawEvent))
})
handler(events, statusCode)
}
Notice how I play there with the objects that .responseJSON provides, and how I get the resulting array from the service by accessing data.result.value (that being said this will depend on the data structure of your service response)
It seems that the output is in Json, so i'll need to map it into an object(or class,whatever you call it). If you think its not worth it, you can convert it into an Dictionary, i think it will work as well
#Gustavo caiafa is right, Mapping it to JSON did the trick. Here's the code for anyone who gets stuck on something similar:
Alamofire.request(submissionURL, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseString() { (response) in
let outputResponseJSON : JSON = JSON.init(parseJSON: response.result.value!)
let outputResponseText = JSON(outputResponseJSON)["Error"].stringValue
switch response.result {
case .success:
print("Validation Successful...\(String(describing: response.value))")
print("response value: \(String(describing: String(outputResponseText)))")
switch outputResponseText {
case "error_none":
outputMessage = "No matching Group Code. If you are having trouble, please go to \nhttps://app.phillyscientists.com"
print(outputMessage)
break
case "error_tooManyIDs":
outputMessage = "Error, please contact developer."
print(outputMessage)
break
case "error_noGroupIDReceived":
outputMessage = "Try Again."
print(outputMessage)
break
default:
let JSONResponse : JSON = JSON.init(parseJSON: response.result.value!)
The answer is using SwiftyJSON for the outputResponseJSON and outputResponseText values.

Alamofire receive and parse an array of strings swift

I getting the result as an array of strings like this
["India","America","Australia","China","Russia"]
And I'm using Alamofire to get the response using code. There's no error, but I got the result as null. Please help in parsing this.
sessionManager?.request(strURL, method: method, parameters: params, encoding: encoding , headers: headers).responseJSON { (response) in
switch response.result {
case .success:
let resJson = JSON(response.result.value!)
success(resJson)
break
case .failure(let error):
failure(error as NSError)
break
}
}
Try this:
if let responseData = response.result.value{
let responsevalue = responseData as? [String]
}
For anyone looking for another derived answer, just put this chunk of code after Alamofire.request(...):
.responseJSON(completionHandler: { (response) in
switch response.result{
case .success(let value):
// Here is your array of String
let arrayOfStrings = value as? [String]
case .failure(let error):
// Some code when error happens...
print(error.localizedDescription)
}
})
This solution using SwiftyJSON:
.responseJSON(completionHandler: { (response) in
switch response.result{
case .failure(let error):
print(error.localizedDescription)
case .success(let res):
let json = JSON(res)
let res = json["result"]
var models = [String]()
if let models1 = company["models"].array {
for model in models1 {
guard let mod = model.string else { return }
models.append(mod)
}
}
}
})

Alamofire 4 Swift 3 GET request with parameters

I'm building a network stack using Alamofire 4 and Swift 3. Following the Alamofire guidelines I've created a router for the endpoints of the services. I'm currently using the free API of OpenWeatherMap but I'm finding problems in order to create a get request.
That's the url needed: http://api.openweathermap.org/data/2.5/weather?q=Rome&APPID=MY_API_KEY. Pasted on a browser, and using a real API Key it works and gives me back my nice json full of info about the weather in the given location.
On my App I can insert the parameters as Dictionary but I cannot find a way to append the api key at the end of the url.
That's my enum router:
enum OWARouter: URLRequestConvertible {
case byCityName(parameters: Parameters)
// MARK: Url
static let baseURLString = "http://api.openweathermap.org"
static let apiKey = "MY_APY_KEY"
static let pathApiKey = "&APPID=\(apiKey)"
var method: HTTPMethod {
switch self {
case .byCityName:
return .get
}
}
var path: String {
switch self {
case .byCityName:
return "/data/2.5/weather"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try OWARouter.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
switch self {
case .byCityName(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
print((urlRequest.url)!)
}
urlRequest.httpMethod = method.rawValue
return urlRequest
}
}
When I log my (urlRequest.url)! I have this: http://api.openweathermap.org/data/2.5/weather?q=Rome but I cannot find a way to add the apiKey.
What am I doing wrong?
I've also made an ugly test adding this code after the print:
var urlRequest2 = URLRequest(url: (urlRequest.url)!.appendingPathComponent(OWARouter.pathApiKey))
print("URL2: \(urlRequest2)")
And the log is URL2: http://api.openweathermap.org/data/2.5/weather/&APPID=My_API_KEY?q=Rome
How come the api key is in the middle?
If you need this is the simple request code:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome"])).responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
print(response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
Another question...
If I use as parameters ["q":"Rome, IT"], my output url is: http://api.openweathermap.org/data/2.5/weather?q=Rome%2CIT
How to keep the comma?
Thank you!
Swift - 5 Alamofire 5.0 Updated Code (just Change AF.request Method according to your requirement you can add Parameters headers and intercepter as well )
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
// handle your code
}
case .failure(let error):
print(error)
}
}
Used below lines of code:
func getRequestAPICall(parameters_name: String) {
let todosEndpoint: String = "your_server_url" + "parameterName=\(parameters_name)"
Alamofire.request(todosEndpoint, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response)
if let data = response.result.value{
// Response type-1
if (data as? [[String : AnyObject]]) != nil{
print("data_1: \(data)")
}
// Response type-2
if (data as? [String : AnyObject]) != nil{
print("data_2: \(data)")
}
}
}
}
func AlamofireGetCode()
{
var url:String!
url = "https://jsonplaceholder.typicode.com/comments"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result{
case .success(let json):
print(json)
DispatchQueue.main.async {
print(json)
self.mainarray = json as? NSArray
print(self.mainarray as Any)
self.mytableviewreload.reloadData()
}
case .failure(let error):
print(error)
}
}
}
I've found a solution... the Api Key is simply a parameter to send to the request. So the code to change is not in the router but in the request function:
Alamofire.request(OWARouter.byCityName(parameters: ["q":"Rome","APPID":"MY_API_KEY"])).responseJSON { response in
print(response.request)
//print(response.response)
//print(response.data)
//print(response.result)
//debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
EDIT: the comma issue do not gives me any problem now. Thank you.
Swift 5+
Use AF.request
let todosEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1"
let request = AF.request(todosEndpoint)
request.responseJSON { (data) in
print("Response", data)
}
**//
Fist in third party liabrary, install pod 'Alamofire'
Using Alamofire get json data
import UIKit
import Alamofire
class APIWRAPPER: NSObject {
static let instance = APIWRAPPER()
func LoginAPI(Uname : String , Password : String) {
let requestString =
"http://************php/v1/sign-in"
let params = ["user_name": Uname,
"password": Password]
Alamofire.request(requestString,method: .get, parameters: params, encoding: JSONEncoding.prettyPrinted, headers: [:]).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil
{
print("response : \(response.result.value!)")
}
else
{
print("Error")
}
break
case .failure(_):
print("Failure : \(response.result.error!)")
break
}
}
}
}

Resources