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,
Related
Because I could just find some outdated information / not working solutions to my problem I decided to ask this kind of question again. (See outdated / wrong solutions:)
WKWebView: Is it possible to preload multiple URLs?
(Xcode, Swift) Is it possible to load multiple WKWebViews simultaneously if they are on different viewControllers?
Swift 3, iOS 10.3 - Preload UIWebView during Launch Screen
My app is separated in one native part and one HTML part. The HTML is saved as a local file (index.html) and should be load into the myWebView view.
#IBOutlet weak var myWebView: UIWebView!
func loadWebview() {
let url = Bundle.main.url(forResource: "index", withExtension: "html")
let request = URLRequest(url: url!)
myWebView.loadRequest(request)
myWebView.scrollView.isScrollEnabled = false
myWebView.allowsLinkPreview = false
myWebView.delegate = self
}
Because my DOM tree is very large, switching from the native part to the web part (on button click) takes quite a long time at -least for the first time switching- because afterward, I'm sure the webView-request gets cached.
To my question: How can I preload the WebView on app init to avoid the white screen (maybe 0.5s - 1s duration) when switching from the native to the Web part?
EDIT:
The WKWebView is displaying the scrollbar while the UIWebView was not!
Using (like with UIWebView) this styles:
::-webkit-scrollbar {
display: none;
}
is not working and adding these lines:
webview.scrollView.showsHorizontalScrollIndicator = false
webview.scrollView.showsVerticalScrollIndicator = false
is also not working at all.
Firstly, you should switch to WKWebView,UIWebView is no longer recommended to be used by Apple.
Secondly, you can create a pool of web views that get created and asked to load when the app starts. This way by the time the user switches to the web interface the web view might've got a chance to fully load.
For this you can use a class like this:
/// Keeps a cache of webviews and starts loading them the first time they are queried
class WebViewPreloader {
var webviews = [URL: WKWebView]()
/// Registers a web view for preloading. If an webview for that URL already
/// exists, the web view reloads the request
///
/// - Parameter url: the URL to preload
func preload(url: URL) {
webview(for: url).load(URLRequest(url: url))
}
/// Creates or returns an already cached webview for the given URL.
/// If the webview doesn't exist, it gets created and asked to load the URL
///
/// - Parameter url: the URL to prefecth
/// - Returns: a new or existing web view
func webview(for url: URL) -> WKWebView {
if let cachedWebView = webviews[url] { return cachedWebView }
let webview = WKWebView(frame: .zero)
webview.load(URLRequest(url: url))
webviews[url] = webview
return webview
}
}
and ask it to preload the url sometimes during the app startup:
// extension added for convenience, as we'll use the index url in at least
// two places
extension Bundle {
var indexURL: URL { return self.url(forResource: "index", withExtension: "html")! }
}
webviewPreloader.preload(url: Bundle.main.indexURL)
Thirdly, you might need to use a container view instead of the actual web view, in your controller:
#IBOutlet weak var webviewContainer: UIView!
What remains is to add the preloaded web view to the container when needed:
func loadWebview() {
// retrieve the preloaded web view, add it to the container
let webview = webviewPreloader.webview(for: Bundle.main.indexURL)
webview.frame = webviewContainer.bounds
webview.translatesAutoresizingMaskIntoConstraints = true
webview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webviewContainer.addSubview(webview)
}
And not lastly, be aware that keeping alive instances of web views, might carry performance penalties - memory and CPU-wise.
A Mac app requires that a HTML file be called in a WebView (the legacy type, not the newer WKWebView) in a localized form to present the user with some content.
As I side note, I realize that WebView should not be used today, and WKWebView is preferred, however this is a legacy app that currently needs support.
I've used a similar method for the iOS version, however it does not seem to be working. The HTML files are simply called "Term.HTML" and are placed in each localization folder alongside the localized string and all other localized content. This is the code I tried to use:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:NSLocalizedString(#"fileTerm", nil) ofType:#"html"];
htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[termsView takeStringURLFrom:htmlString];
Where my localized strings file each contain a line that says:
"fileTerm" = "Term";
This is what links the declaration of the first line to the actual file. It works in iOS. However, when running the app and the view containing the WebView attempt to the run, XCode will automatically create a breakpoint on the third line when I actually attempt to give the HTML file to "termsView" which is my WebView. After skipping this breakpoint, and forcing the app to run, the whole view containing the WebView will simply not appear. I would be thankful if anyone knew why this was or if there was a better way to do this? Thank you everyone!
may be someone needs in SWift: I solved this problem with saving 3 html file for every language, and then in ViewController class checked current app language. And called up the html file for current language
func loadHtmlFile() {
let preferredLanguage = NSLocale.preferredLanguages[0]
if preferredLanguage == "kz" {
let url = Bundle.main.url(forResource: "aboutUs_kz", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
if preferredLanguage == "ru" {
let url = Bundle.main.url(forResource: "aboutUs_ru", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
if preferredLanguage == "en" {
let url = Bundle.main.url(forResource: "aboutUs_en", withExtension:"html")
let request = URLRequest(url: url!)
webView.load(request)
}
}
in viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
loadHtmlFile()
}
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)
Go easy on me I am new to I OS and Swift :). I am trying to create a IOS app using swift. I have a web view display that is working correctly, displaying the website. YAY!!
What I need to do now is create a unique identifier that is stored locally and when the app is opened is sent to the remote server. I see i can use this...
UIDevice.currentDevice().identifierForVendor!.UUIDString
However i would like to store it locally for future use and send it to the remote server every time the app is opened. I have done research on this and have come upon answers for other objects just not a web view.
If someone knows of a tutorial or example code for this solution i would greatly appreciate it.
UPDATE
let uuid = UIDevice.currentDevice().identifierForVendor!.UUIDString
and for the url im using
let url= NSURL (string:"https://example.com");
Could i do something like this? Or like it?
let url= NSURL (string:"https://example.com");
let requestobj= NSURLRequest(URL:url! ADD VAR HERE? );
Where ADD VAR HERE is the uuid to pass to the server which i can catch with a php script?
Latest update..
Im having a hard time integrating that into my existing code. Where would be the best place to put it?
import UIKit
class ViewController: UIViewController {
let uuid = UIDevice.currentDevice().identifierForVendor!.UUIDString
#IBOutlet weak var WebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL (string: "https://example.com");
let requestObj = NSURLRequest(URL: url?)
WebView.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is the answer i was looking for. Thanks for your help everyone!
let device_uuid = UIDevice.currentDevice().identifierForVendor!.UUIDString
let api_host = "https://example.com?uuid=" + device_uuid
let url = NSURL(string: api_host)
let req = NSURLRequest(URL: url!)
WebView.loadRequest(req);
Apparently what i needed to do was build my URL into a variable. Then i can structure it using the NSURL and use it from there. This guide helped me. Just ignore the ruby on rails part if that's not what your doing.
http://ericlondon.com/2015/12/09/sending-messages-between-a-swift-webview-and-a-rails-backend-using-javascript.html
You will need to check on the webserver side to confirm exactly what you need to pass in - but if you are developing that side as well, then you should have control :-)
Should be something like this - please not that you don't need ; in swift
let request= NSURLRequest(URL:url)
var bodyData = "myUUID=\(uuid)&otherData=value1"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
Keep in mind that this identifier will change if a user uninstalls the application. If you need to persist it then I'd recommend to store it on the keychain so the id is always the same for the same phone even if the app is uninstalled.
Check this other question: How to preserve identifierForVendor in ios after uninstalling ios app on device?
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