I use WKWebview to load a URL.
let webView = WKWebview()
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url!)
webView.loadRequest(request)
How can I detect if the link the webView should load is broken?
You can use canOpenUrl method:
UIApplication.sharedApplication().canOpenURL(url)
It will do the url validation and if the link is ok it returns true.
It's mostly use before you call:
UIApplication.sharedApplication().openURL(url)
to make sure this link can be open in safari but it should help you here too.
Make sure the link starts with http:// or https://.
Edited:
It will just check is the link is a correct url.
If you want to see the page is offline, authorisation issues, etc. you can implement WKNavigationDelegate protocol and check out this method:
- webView:didFailNavigation:withError:
this should give you more info.
It's always good idea to use: str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAl‌​lowedCharacterSet())!
it make sure that you don't pass a character which are not allowed in URL.
Edited 2:
To detect the status code you can try to implement:
- webView:decidePolicyForNavigationResponse:decisionHandler:
the navigation response is an NSURLResponse instance but
whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class so you should cast it to NSHTTPURLResponse. That should give you a statusCode.
In the last line in the method you should call handler, for example decisionHandler(WKNavigationResponsePolicyAllow).
Ref: Answer exists here
if let url = NSURL(string: yourUrlString) {
var canOpen = UIApplication.sharedApplication().canOpenURL(url)
}
If you want to check if url string is correct and valid - just create NSURL object, if path contains error it will cast to nil:
let string = "http://google.com"
let url = NSURL(string: string)
let brokenString = "http:\\brokenurl.12"
let brokenUrl = NSURL(string: brokenString) // nil - it's not valid!
If you have implemented NSURLConnectionDelegate then below solution can be used.
didFailWithError method of NSURLConnectionDelegate can be used for this.
This method get called if an error occurs during the loading of a resource.
Can refer to below link
https://developer.apple.com/documentation/foundation/nsurlconnectiondelegate/1418443-connection
Related
I have webView in which I load some url. I need to set custom header for that URLRequest. For the first request it works as expected, header is received on server side and content is displayed accordingly. However if I open another link from displayed page, headers are lost and request is sent without header.
My lucky guess is that, header is added only for the first time and I have to add it every time when request to load url is sent. However I couldn't find method where can I do so.
Currently I'm setting header in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
let url = URL(string: "https://mywebsite.com");
var requestobj = URLRequest(url: url!);
requestobj.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
myWebView.loadRequest(requestobj);
}
Am I missing something or should I add header in different place for every request?
Yes, you should add custom headers each time when you create request.
Ok, thanks to iphonic, to pointing at shouldStartLoadWith. I could use that to understand is request new or old one and solve my problem by doing so:
func webView(_ webView: UIWebView,
shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool{
if(navigationType == UIWebViewNavigationType.linkClicked)
{
var req = request;
req.addValue("my_request_id", forHTTPHeaderField: "X-Requested-With");
self.myWebView.loadRequest(req);
return false;
}
else {
return true;
}
}
So here I check, if navigation type is clickedLink, then I don't load current request, instead I copy it, reapply custom header and load it into myWebView.
If navigationType isn't linkClicked, I proceed request without changes.
I think I know what was my problem but I couldn't find a solution for it.
On my app, you can see that there is a YouTube video, but when you click on it, it won't play the video. Here's the line of code that may cause the issue:
webView.loadHTMLString(partyRock.videoURL, baseURL: nil)
I think that sending nil to the baseURL may cause the issue, but I'm not sure what to replace with.
Thanks
Why are you using loadHTMLString? This property sets the main page content and base URL and I don't think you want to do that.
Use this instead:
let requestURL = URL(string: partyRock.videoURL)
let request = URLRequest(url: requestURL!)
webView.loadRequest(request)
let request = URLRequest(url: URL(string: "https://www.youtube.com/watch?v=KBcIKsJBo2Y")!)
webView.loadRequest(request)
Problem :
actually i am getting url link from api response. and by that link i am loading webview. but when webview load its also showing advertisement so is there any possible way to remove that ad from my webview?
here is my code
override func viewDidLoad() {
super.viewDidLoad()
let url : NSURL = NSURL(string: webviewurl)!
let request : NSURLRequest = NSURLRequest(URL: url)
myweb.loadRequest(request)
}
let me know if is there any possible way to remove ad from webview or may be from url
Usually, you can't change the content of webview you get because what you actually get is a HTML file and then rendered as a webpage.
If the ad only exists in mobile phone, there may be a DNS hijacking,
I'm pulling a URL from a string and turning that into a button to a WebView of the link.
This is the error I'm getting...
2015-11-10 18:58:05.159 MPSTApp[520:169178] -canOpenURL: failed for URL: "https:/www.facebook.com/prontosantateresa -- file:///" - error: "This app is not allowed to query for scheme file"
For this instance the string is https://www.facebook.com/prontosantateresa but I believe it's using the double // as an escape character.
The code calling the url link is such -
var anchorLink: String?
func loadWebPage(){
let requestURL = NSURL(string: anchorLink!)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
}
It's exactly what the error message says: It tries to open a file:// url. So, your algorithm for retrieving the https:// url seems to do something wrong and turn "//" into "/". It could also come handy to add the NSAllowArbitaryLoads key to your Info.plist.
I investigated issue. Since I was using an app browser, it didn't need to use UIApplication.canOpenUrl().
So, to resolve this I replaced the event method with below code in
#IBAction func website1ButtonPressed(sender: UIButton) {
if self.anchorLink != nil{
self.performSegueWithIdentifier("categoryDetailToWebSegue", sender: nil)
}
}
Hi I am really new to coding in Swift, and am trying to follow the codes in this book: http://www.apress.com/9781484202098. Learn iOS 8 App Development 2nd Edition by James Bucanek
In particular, I am working through Chapter 3 - building a URL shortening app, but despite having copied the code exactly, I am getting an error on the code in Page 76:
if let toShorten = webView.request.URL.absoluteString {
which states 'NSURLRequest?' does not have a member named 'URL'.
I have tried googling an answer, but unfortunately have not come across anything. Any response I can find seems to suggest that my code ought to be working (e.g. How to get url which I hit on UIWebView?). This seems to have the closest answer SWIFT: Why I can't get the current URL loaded in UIWebView? but the solution does not appear to work for me. If I add a ? after the request, it will then at least build it, but I then have a nil variable returned.
I am using Xcode v6.1.1. Here is the piece of code that is coming up with the error in ViewController.swift:
let GoDaddyAccountKey = "0123456789abcdef0123456789abcdef" //this is replaced by my actual account key in my own code
var shortenURLConnection: NSURLConnection?
var shortURLData: NSMutableData?
#IBAction func shortenURL( AnyObject ) {
if let toShorten = webView.request?.URL.absoluteString { // ? now added
let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) //added if here and removed !
let request = NSURLRequest(URL:firstrequest)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
If you have any suggestions on how I can fix this, I would really appreciate it!
Update:
Following suggestions from Ashley below, I have amended my code so that it is no longer bringing up the error (see comments above). However, it is now no longer running. This appears to be because the urlString is being created as http://api.x.co/Squeeze.svc/text/d558979bb9b84eddb76d8c8dd9740ce3?url=Optional("http://www.apple.com/"). The problem is therefore the Optional() that is included and thus makes it an invalid URL. Does anyone have a suggestion on how to remove this please?
request is an optional property on UIWebView:
var request: NSURLRequest? { get }
also stringByAddingPercentEscapesUsingEncoding returns an optional:
func stringByAddingPercentEscapesUsingEncoding(_ encoding: UInt) -> String?
What you need is to make user of optional binding in a few places:
if let toShorten = webView.request?.URL.absoluteString {
if let encodedURL = toShorten.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlString = "http://api.x.co/Squeeze.svc/text/\(GoDaddyAccountKey)?url=\(encodedURL)"
shortURLData = NSMutableData()
if let firstrequest = NSURL(string: urlString) { // If a method can return a nil, don't force unwrap it
let request = NSURLRequest(URL:first request)
shortenURLConnection = NSURLConnection(request:request, delegate:self)
shortenButton.enabled = false
}
}
}
See Apple's docs on optional chaining for details
See Apple's docs for NSURL class