Add parameters to URL (resource from path, WKWebView) - ios

I am using Swift 4 & WKWebView. The HTML pages are included in the app (not downloaded from server).
For configuration purpose I would like to add parameters to the URL (e.g. ...index.html?debug=true).
Currently I am using the following approach to load the page:
let indexHTMLPath = Bundle.main.path(forResource: "f7Shoma/index", ofType: "html")
let url = URL(fileURLWithPath: indexHTMLPath!)
let request = URLRequest(url: url)
...
appWebView!.load(request)
How can parameters be added/passed to the page?

You can use URLComponents to create a URL with a query component:
var components = URLComponents(string: indexHTMLPath)
components?.queryItems = [URLQueryItem(name: "debug", value: "true")]
if let result = components?.url {
let request = URLRequest(url: url)
appWebView!.load(request)
}

Related

URLRequest to Alamofire URLConvertible

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)
}

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 save UIWebView content for offline display?

I'm using Xcode 7.2 and Swift to create an iOS app, on this app I display the content of my website, however if I was offline the content will not be shown. So I want to cache the webpage and display for offline.
After I declared everything I'm using the following code :
var URLPATH="http://google.com"
let requestURL = NSURL(string: URLPATH)
let request = NSURLRequest(URL: requestURL!)
WB.loadRequest(request)
HTML to Data
if let url = URL(string: urlString) {
person.setValue(try? Data(contentsOf: url), forKey: "content_article")
}
Data to WebView
if let savedObject = fetchedObjects?.first,
let data = savedObject.content_article as? Data,
let baseStringUrl = savedObject.content_url,
let baseURL = URL(string: baseStringUrl) {
webView.load(
data, mimeType: "text/html",
textEncodingName: "",
baseURL: baseURL
)
}

iOS Swift NSURL Web Address Not Working

I'm attempting to get data from a server. My URL is (for example): http://dommain.com/action
When I execute
let nsURL = NSURL(fileURLWithPath: url)
the URL gets translated into http:/domain.com/action. Then when I execute this:
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL) {
(data, response, error) in
print("data=\(data) response=\(response) error=\(error)")
}
the error property says it can't find "file:///http:/domain.com/action
I'm not sure what I'm doing wrong.
Replace
let nsURL = NSURL(fileURLWithPath: url)
with
let nsURL = NSURL(string: url)
An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
NSURL(fileURLWithPath: url) initializes and returns a newly created NSURL object as a file URL with a specified path. For network URL use NSURL(string: url) instead.
For Swift 3 and upwards, use URL instead of NSURL:
let u = URL(string: url)

Resources