I am a beginner of Swift and trying to develop web view app
the website in the web view have popups , so I also put some code for pop up
but when I run this app ,the screen is like that picture below
I tried
"mainView = WKWebView(frame : UIScreen.main.bounds
,configuration: configuration)"
then this app shows full screen but does not show tool bar
could you guys help me what I should try ...
here is codes
let preferences = WKPreferences()
preferences.javaScriptEnabled = true
preferences.javaScriptCanOpenWindowsAutomatically = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
mainView = WKWebView(frame :
CGRect.init(x: 0, y: 0, width: self.mainView.frame.size.width, height: self.mainView.frame.size.height)
,configuration: configuration)
mainView.uiDelegate = self
mainView.navigationDelegate = self
view.addSubview(mainView)
self.webViews.append(self.mainView)
let mainURL = URL(string: url)
let mainRequest = URLRequest(url: mainURL!)
self.mainView.load(mainRequest)
func webView(_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
guard let frame = self.webViews.last?.frame else {
return nil
}
return createWebView(frame: frame, configuration: configuration)
}
func createWebView(frame: CGRect, configuration: WKWebViewConfiguration) -> WKWebView {
var webView = WKWebView(frame: frame, configuration: configuration)
print("createWebView ")
// set delegate
// webView = WKWebView(frame: frame, configuration: configuration)
// webView.autoresizingMask = [.flexibleWidth , .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
webView.scrollView.alwaysBounceVertical = false
webView.scrollView.bounces = false
self.view.addSubview(webView)
self.webViews.append(webView)
return webView
}
Related
I am using Swift 4.1 and I am wondering how to pass the url data that is given here:
func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
}
into my subclass of UIViewController I called HotSpotRISViewController. Here is what I attempted:
func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let vc = HotSpotRISViewController()
vc.setURL(theURL: url)
let navigationController = UINavigationController(rootViewController: vc)
self.window!.rootViewController = navigationController
}
My HotSpotRISViewController contains this function:
func setURL(theURL: URL) {
self.url = theURL
print(self.url ?? "nil")
}
Inside my HotSpotRISViewController I have a property of type URL ready to be set. The above code correctly passes the info, because my print statement prints out the URL, but I get a black screen instead of my app. What am I missing? And then on the other hand, the following makes the app start up correctly but I have no idea how to pass the url data using this method:
func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = mainStoryboard.instantiateInitialViewController()
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
I'm wondering how I can get both my app started up correctly without a black screen and pass the url data. Thank you.
You can add a global variable in your appDelegate file and fetch it with your setURL function :
In your AppDelegate.swift
var myurl: URL!
....
func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
self.myurl = url
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = mainStoryboard.instantiateInitialViewController()
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
...
In your HotSpotRISViewController.swift
func setURL(theURL: URL) {
DispatchQueue.main.async {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
self.url = appDelegate.myurl
}
}
I am creating pdf from an html file with images.I tried creating from from Html as well as from UIWebView by loading the html in to web view .The following are the methods use for both approach
1.From html
func exportHTMLContentToPDF(HTMLContent: String) {
let printPageRenderer = CustomPrintPageRenderer()
let printFormatter = UIMarkupTextPrintFormatter(markupText: HTMLContent)
printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAtIndex: 0)
let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer)
pdfData.writeToFile(pdfPath(), atomically: true)
}
2.From UiWebView by loading Html
func createPdfFromViewFormatter(viewFormatter:UIViewPrintFormatter) {
let printPageRenderer = CustomPrintPageRenderer()
printPageRenderer.addPrintFormatter(viewFormatter, startingAtPageAtIndex: 0)
let pdfData = drawPDFUsingPrintPageRenderer(printPageRenderer)
pdfData.writeToFile(pdfPath(), atomically: true)
}
Pdf creation method`
private func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
let data = NSMutableData()
UIGraphicsBeginPDFContextToData(data, CGRect(x: 0.0, y: 0.0, width: printPageRenderer.printableRect.width, height: printPageRenderer.printableRect.height), nil)
printPageRenderer.prepareForDrawingPages(NSRange(location: 0, length:printPageRenderer.numberOfPages() ))
for i in 0..<printPageRenderer.numberOfPages() {
UIGraphicsBeginPDFPage()
printPageRenderer.drawPageAtIndex(i, inRect: UIGraphicsGetPDFContextBounds())
}
UIGraphicsEndPDFContext()
return data
}
The issue is the image in the html is is not shown in the created pdf.But it is displayed while loading it in a UIWebView.
I'm having the same problem :
IOS Swift sharing PDF documents with images
I believe it's a bug. The only solution I found so far is to create a dummy UIWebView that I hide. I load the HTML in the UIWebView and then create the PDF. Here is my code :
override func viewDidLoad() {
super.viewDidLoad()
hiddenWebView.loadHTMLString(htmlText, baseURL: nil)
hiddenWebView.isHidden = true
}
override func viewDidAppear(_ animated: Bool) {
pdfDocument = getPdf()
let tmpDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
let fileURL = tmpDirectoryURL.appendingPathComponent("document.pdf")
pdfDocument.write(to: fileURL, atomically: false)
documentWebView.loadRequest(URLRequest(url: fileURL))
}
I hope it helps.
I faced same issue and finally I got the solution. Hope anyone help this solution. Just Replace createPdfFromViewFormatter methods 's code.
`
func createPdfFromViewFormatter(viewFormatter:UIViewPrintFormatter) {
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(formatter, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext()
// 5. Save PDF file
let path = "\(NSTemporaryDirectory())\(filename).pdf"
pdfData.write(toFile: path, atomically: true)
}
`
Call createPdfFromViewFormatter method Like That
let pdfData = createPdfFromViewFormatter(viewFormatter: webView!.viewPrintFormatter())
I'm creating a Slideout navigation controller.
Now I need to assign my MenuViewController and my TopViewController.
I have a TopViewController screen in a Storyboard that was using other type of slideout menu.
In my AppDelegate I have the following:
let storyboard : UIStoryboard! = UIStoryboard(name: "Main", bundle: nil)
let dashboard = storyboard.instantiateViewControllerWithIdentifier("DashboardView") as! DashboardViewController
let menu : SlideoutViewController = SlideoutViewController()
menu.menuEnabled = true
menu.topView = dashboard
menu.menuView = SalesViewController()
UIApplication.sharedApplication().keyWindow?.rootViewController = menu as SlideoutViewController
But when doing this the viewDidLoad method in DashboardViewController is never reached, that means that the view has not been instantiated yet.
Any clue?
UPDATE: this is a function selectView in slideout view controller
func selectView(viewController: UIViewController){
if (_internalTopNavigation != nil)
{
_internalTopNavigation!.removeFromParentViewController();
_internalTopNavigation!.view.removeFromSuperview();
}
_internalTopNavigation = UINavigationController(rootViewController: viewController)
_internalTopNavigation!.view.frame = CGRect(x: 0, y: 0,
width: _internalTopView!.view.frame.width,
height: _internalTopView!.view.frame.height)
_currentView = viewController;
_internalTopView!.addChildViewController(_internalTopNavigation!);
_internalTopView!.view.addSubview(_internalTopNavigation!.view);
if (_menuEnabled == true)
{
viewController.navigationItem.leftBarButtonItem = createMenuButton()
viewController.navigationItem.leftBarButtonItem!.tintColor = UIColor.blueColor()
}
_externalContentView = viewController;
}
When I set the externalMetadata on my AVPlayerItem and load it into the player of AVPlayerViewController it loads my metadata in the Info but the text is faded http://drop.lyokotech.com/image/0F0V2W1c431A/Screen%20Shot%202015-11-10%20at%2014.30.03.png
Any idea why this would happen? This is how I am loading it (From the root view controller)
func getMetadata() -> [AVMetadataItem] {
var items = [AVMetadataItem]()
func createMetaDataItem(key: String, value: String) -> AVMetadataItem {
let data = AVMutableMetadataItem()
data.key = key
data.value = value
data.keySpace = AVMetadataKeySpaceCommon
data.locale = NSLocale.currentLocale()
return data
}
let title = createMetaDataItem(AVMetadataCommonKeyTitle, value: "SOME TITLE")
let description = createMetaDataItem(AVMetadataCommonKeyDescription, value: "SOME DESCRIPTION")
items.append(title)
items.append(description)
return items
}
let metadata = getMetadata()
if let path = NSBundle.mainBundle().pathForResource("IMG_0343", ofType: "MOV") {
let url = NSURL(fileURLWithPath: path)
let item = AVPlayerItem(URL: url)
item.externalMetadata = metadata
let player = AVPlayer(playerItem: item)
let av = AVPlayerViewController()
av.player = player
av.player?.play()
presentViewController(av, animated: true, completion: nil)
}
This happens whether I use a local file or a stream (HLS)
This is due to a problem in a simulator. It will work fine on a real device.
I have a UIWebView containing html-formatted text. In the text some words are links. When clicked on they should push another view on to the stack. How should I write the html link and corresponding objective-c code to make this work?
Set up delegate for UIWebView, then you can handle link action clicked:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
[self.navigationController pushViewController:vc animated:YES];
return NO;
}
return YES;
}
Swift 3: Full UIWebView example to push a view in stack and open another html file in bundle when clicked on html link e.g. imprint
class WebViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
var filename:String?
override func viewDidLoad() {
super.viewDidLoad()
guard filename != nil else {
fatalError("filename not defined")
}
view.backgroundColor = UIColor.white
webView.isOpaque = false;
webView.delegate = self
webView.backgroundColor = UIColor.clear
//remove file extension first
filename = filename!.replace(".html", replacement: "")
let localfilePath = Bundle.main.url(forResource: filename, withExtension: "html")
let myRequest = NSURLRequest(url: localfilePath!)
webView.loadRequest(myRequest as URLRequest)
}
...
}
extension WebViewController: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
//set view title from html document
let pageTitle = webView.stringByEvaluatingJavaScript(from: "document.title")
navigationItem.title = pageTitle
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .linkClicked,
let urlStr = request.url?.absoluteString,
!urlStr.contains("http://"),
let filename = request.url?.lastPathComponent, //e.g. imprint.html
let vc = storyboard?.instantiateViewController(withIdentifier: "WebView") as? WebViewController{
vc.filename = filename
self.navigationController?.pushViewController(vc, animated: true)
return false
}
return true
}
}