URLRequest to Alamofire URLConvertible - ios

I have found the same question but not worked for me. thats why I'm posting this again.
The following code gives me an error.
Could not cast value of type 'Foundation.URLRequest' to 'Alamofire.URLConvertible'
the code sample:
let url = (wURL).replacingOccurrences(of: "(f_id)", with: String(conID))
let _url = URL(string: url)
var urlRequest = URLRequest(url: _url!)
urlRequest.timeoutInterval = TimeInterval(exactly: 30)!
let finalUrl = urlRequest as! URLConvertible
What am I missing?

You can't do it, because for URLRequest there is special protocol URLRequestConvertible.
let realURL: URL = URL(string: "https://google.com")!
let url: Alamofire.URLConvertible = realURL
let urlRequest: Alamofire.URLRequestConvertible = URLRequest(url: realURL)
AF.request(urlRequest).responseJSON {
print($0)
}

Related

Swift iOS15 async/await + basic authentication + http request slow(er)

I am using the below code for basic http authentication. It is noticeably slower than when I wasn't using authentication (the below is called around 30 times)
Are there any speed optimization changes that could be made to the code ?
Thanks
struct PrixJSONService {
let passwordString = "user:password"
let configuration = URLSessionConfiguration.default
enum PrixJSONServiceError: Error {
case failed
case failedToDecode
case invalidStatusCode
}
func fetchPrix(for stationId:String) async throws -> [Prix] {
let passwordData = passwordString.data(using:String.Encoding.utf8)!
let base64EncodedCredential = passwordData.base64EncodedString()
let authString = "Basic \(base64EncodedCredential)"
let session = URLSession(configuration: configuration)
configuration.httpAdditionalHeaders = ["Authorization" : authString]
let dataUrl = "https://xxxx.xx/~xx/xxxxxxxx/prix/\(stationId)/price.json"
let url = URL(string: dataUrl)!
var urlRequest = URLRequest(url: url)
urlRequest.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
urlRequest.httpMethod = "GET"
let (data, response) = try await session.data(for: urlRequest)
guard let response = response as? HTTPURLResponse,
response.statusCode == 200 else {
throw PrixJSONServiceError.invalidStatusCode
}
let decodedData = try JSONDecoder().decode([Price].self, from: data)
return decodedData
}
}

Date String causing error in NSMutableURLRequest URL using swift language

I am passing date after converting to String but causing error
unexpectedly found nil while unwrapping a value
this is code of Request
let url = SERVICE_URL + "GetHistoryDataByTerminalNo?TerminalNo=\(VehicleList.SelectedTerminal.selectedTerminalId)&fromDate=\(fromDateText)&toDate=\(endDateText)"
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 30.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
UPDATE
I am getting this URL
http://labs2.unitedtracker.com/api/Trackers/GetHistoryDataByTerminalNo?TerminalNo=351535058776063&fromDate=2020-08-23 14:15:52.000&toDate=2020-08-23 16:15:52.000
You cannot just put a string with a space into a URL, you have to URL-encode it first.
First of all, add extension for URL encoding:
extension String {
public var urlEncoded: String {
var allowedCharacters = CharacterSet.urlQueryAllowed
allowedCharacters.remove(charactersIn: "!*'();:#&=+$,/?%#[]")
return addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? ""
}
}
Second, encode the parameter values:
let url = SERVICE_URL + "GetHistoryDataByTerminalNo?TerminalNo=\(VehicleList.SelectedTerminal.selectedTerminalId.urlEncoded)&fromDate=\(fromDateText.urlEncoded)&toDate=\(endDateText.urlEncoded)"
Or, you could use URLComponents and URLQueryItem to generate your URL.
I would recommend not messing around with URL encoding manually - we have URLComponents for this.
For example:
let SERVICE_URL = "https://example.com/service/"
let url = SERVICE_URL + "GetHistoryDataByTerminalNo"
var components = URLComponents(string: url)!
components.queryItems = [
URLQueryItem(name: "TerminalNo", value: VehicleList.SelectedTerminal.selectedTerminalId),
URLQueryItem(name: "fromDate", value: fromDateText),
URLQueryItem(name: "toDate", value: toDateText)
]
let request = URLRequest(url: components.url!, timeoutInterval: 30)
(you probably want a little more error checking)
Also, as #Joakim mentioned, don't use NS... types if you can avoid them.

crash uiwebview without http or https in swift [duplicate]

This question already has answers here:
Add http:// to NSURL if it's not there
(5 answers)
Closed 5 years ago.
I want show the URL in Web View
here is my code
let urlString:String = "https://www.apple.com"
let url:URL = URL(string: urlString)!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
urlTextField.text = urlString
if user forget to write http or https the app crashed how can I resolve this error
Just use starts(with:) on string to detect if the url string starts with http/https, and if not, add the "http://" yourself (also, use safe if let instead of force unwrap):
var urlString: String = "www.apple.com"
if !urlString.starts(with: "http://") && !urlString.starts(with: "https://") {
urlString = "http://\(urlString)"
}
if let url: URL = URL(string: urlString) {
let urlRequest: URLRequest = URLRequest(url: url)
webView.load(urlRequest)
urlTextField.text = urlString
}

How to pass the parameters for switch controller to server in swift programmatically?

let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = ["userId":userId.text!,"status":"offline"] as Dictionary<String,String>
var err:NSError!
do{
theRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: [])
}
catch let error as NSError
{
err = error
theRequest.HTTPBody = nil
}
theRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
theRequest.addValue("application/json", forHTTPHeaderField: "Accept")
How to pass the parameter for switch control to server?
to pass the value of the bool, you need to pass it as another parameter into the function. for example, right now you have:
let url = NSURL(string: urlString)
change it to:
let url = NSURL(string: urlString, value1: Bool)
then, when you call this post function from your view controller, you need to get the current state of the bool value that corresponds to the value of the switch. You can do that like so:
let value = yourBool.boolValue()
then, in your post function, do something like this:
let url = NSURL(string: urlString, value1: Bool)
var status = String()
if value1 == true {
status = "online"
}
else {
status = "offline"
}
let theRequest = NSMutableURLRequest(URL: url!)
let parameters = ["userId":userId.text!,"status":status]

How to send Json as parameter in url using swift

I am new in swift language. I looked at some questions for parsing Json in swift in here but my issue is alittle different from others.
when i write /cmd=login&params{'user':'username','password':'pass'} it returns correct data. how to resolve this in swift
I send username and password to url as json but
it retrieve error which means "invalid format "
Please help me.
Here is what i have tried:
var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
} else {
println("No HTTP response")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil {
println("error=\(error)")
return
}
println("****response= \(response)")
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("**** response =\(responseString)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary
}
task.resume()
Assuming based on your question that the format the server is expecting is something like this:
http://<host>?cmd=login&params=<JSON object>
You would need to first URL-encode the JSON object before appending it to the query string to eliminate any illegal characters.
You can do something like this:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login&params=\(urlEncoadedJson)")
Let's say url is
https://example.com/example.php?Name=abc&data={"class":"625","subject":"english"}
in Swift 4
let abc = "abc"
let class = "625"
let subject = "english"
let baseurl = "https://example.com/example.php?"
let myurlwithparams = "Name=\(abc)" + "&data=" +
"{\"class\":\"\(class)\",\"subject\":\"\(subject)\"}"
let encoded =
myurlwithparams.addingPercentEncoding(withAllowedCharacters:
.urlFragmentAllowed)
let encodedurl = URL(string: encoded!)
var request = URLRequest(url: encodedurl!)
request.httpMethod = "GET"
I don't think you need to encode your JSON the way you're doing it. Below should work.
let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
var url:NSURL = NSURL(string: "http://<host>?cmd=login&?\(jsonString)")!
//var session = NSURLSession.sharedSession()
var responseError: NSError?
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
// var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
var response: NSURLResponse?
request.HTTPMethod = "POST"
You json string is not valid, it should be like:
let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
As for the request, I think GET it what you really need:
var urlString = "http://<host>" // Only the host
let payload = "?cmd=login&params=" + jsonString // params goes here
urlString += payload
var url:NSURL = NSURL(string: urlString)!
// ...
request.HTTPMethod = "GET"

Resources