我是Xcode新手,不知道如何在iPhone X的safe area设置webview,我已经通过几个不同的答案,但他们没有帮助。我对这个应用程序的唯一了解是, View 是通过编程方式设置的。下面是我的 ViewController.swift 文件。
import UIKit
import WebKit
import AVFoundation
class ViewController: UIViewController, WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate
{
var webView = WKWebView()
var containerView = WKWebView() //Footer Webview
override func loadView()
{
super.loadView()
}
override func viewDidLoad()
{
super.viewDidLoad()
let theConfiguration = WKWebViewConfiguration()
//Bind Swift and Javascript interface through MessageHandler IOSJSObject
theConfiguration.userContentController.add(self, name: "IOSJSObject")
/* Webview intialization Start */
webView = WKWebView(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-65), configuration: theConfiguration)
containerView = WKWebView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height-45, width: UIScreen.main.bounds.width, height: 45), configuration: theConfiguration)
/* Webview intialization End */
/* Error Page Code Start */
if(TestConnection.isConnectedToNetwork())
{
let url:URL = URL(string:"example.com")!
let request :URLRequest = URLRequest(url:url)
if let navController = self.navigationController
{
navController.popViewController(animated: true)
}
webView.load(request)
}
else
{
let path = Bundle.main.path(forResource: "error-connection", ofType: "html")
let text = try? String(contentsOfFile:path!, encoding: String.Encoding.utf8)
webView.loadHTMLString(text!, baseURL: nil)
}
/* Error Page Code End */
self.view.backgroundColor = UIColor.white
/* Container View Border Code Start*/
let myColor : UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
self.containerView.layer.borderColor = myColor.cgColor;
self.containerView.layer.borderWidth = 0.5
/* Container View Border Code End*/
/* Container View Button Home Back Refresh Code Start*/
let home = UIImage(named: "nptl-home.png")
let back = UIImage(named: "nptl-back.png")
//let refresh = UIImage(named: "nptl-refresh.png")
let homeButton = UIButton()
let backButton = UIButton()
//let refreshButton = UIButton()
homeButton.setImage(home, for: UIControlState())
homeButton.setTitleColor(UIColor.blue, for: UIControlState())
backButton.setImage(back, for: UIControlState())
backButton.setTitleColor(UIColor.blue, for: UIControlState())
//refreshButton.setImage(refresh, for: UIControlState())
//refreshButton.setTitleColor(UIColor.blue, for: UIControlState())
homeButton.frame = CGRect(x: (UIScreen.main.bounds.width/4)-50, y: 4, width: 37, height: 37)
homeButton.addTarget(self, action: #selector(ViewController.home(_:)), for: UIControlEvents.touchUpInside)
backButton.frame = CGRect(x: (UIScreen.main.bounds.width/1.33)+13, y: 4, width: 31, height: 37)
backButton.addTarget(self, action: #selector(ViewController.goBack(_:)), for: UIControlEvents.touchUpInside)
//refreshButton.frame = CGRect(x: UIScreen.main.bounds.width-60, y: 4, width: 48, height: 37)
//refreshButton.addTarget(self, action: #selector(ViewController.doRefresh(_:)), for: UIControlEvents.touchUpInside)
containerView.addSubview(homeButton)
containerView.addSubview(backButton)
//containerView.addSubview(refreshButton)
/* Container View Button Home Back Refresh Code End*/
self.view.addSubview(webView)
self.view.addSubview(containerView)
webView.navigationDelegate = self
webView.uiDelegate = self
webView.scrollView.bounces = false //No Bounce of Webview Screen From Top
if(TestConnection.isConnectedToNetwork())
{
checkUpdate()
}
}
func webView(_ webView: WKWebView,didFailProvisionalNavigation navigation: WKNavigation!,withError error: Error)
{
viewDidLoad()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
{
if let messageBody:NSDictionary = message.body as? NSDictionary
{
print(" \(message.body)")
let myActionName = messageBody["actionName"] as! String
if myActionName == "shareApp"
{
let myShareAppSubject = messageBody["shareAppSubject"] as! String
let myShareAppUrl = messageBody["shareAppURL"] as! String
shareApp(myShareAppSubject,shareAppUrl:myShareAppUrl)
}
else if myActionName == "rateApp"
{
rateApp()
}
else if myActionName == "shareAppPage"
{
let myShareAppMessageSubject = messageBody["shareAppPageMessageSubject"] as! String
let myShareAppMessageURL = messageBody["shareAppPageMessageURL"] as! String
shareAppPage(myShareAppMessageSubject, shareAppPageURL: myShareAppMessageURL)
}
else if myActionName == "error"
{
viewDidLoad()
}
else if myActionName == "loadFromBaseUrl"
{
viewDidLoad()
}
}
}
func webView(_ webView: WKWebView,didStartProvisionalNavigation navigation: WKNavigation!)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
/* Stop the network activity indicator when the loading finishes */
func webView(_ webView: WKWebView,didFinish navigation: WKNavigation!)
{
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (@escaping (WKNavigationActionPolicy) -> Void))
{
if navigationAction.request.url?.scheme == "tel"
{
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
return
}
if navigationAction.request.url?.scheme == "mailto"
{
UIApplication.shared.openURL(navigationAction.request.url!)
decisionHandler(.cancel)
return
}
decisionHandler(.allow)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Start Of Custom bottomfooter
@objc func doRefresh(_: AnyObject)
{
print("Refresh");
webView.reload()
}
@objc func goBack(_: AnyObject)
{
if webView.canGoBack
{
webView.goBack()
}
}
@objc func home(_: AnyObject)
{
//viewDidLoad()
if(TestConnection.isConnectedToNetwork())
{
let url:URL = URL(string:"example.com")!
let request :URLRequest = URLRequest(url:url)
if let navController = self.navigationController
{
navController.popViewController(animated: true)
}
webView.load(request)
}
else
{
let path = Bundle.main.path(forResource: "error-connection", ofType: "html")
let text = try? String(contentsOfFile:path!, encoding: String.Encoding.utf8)
webView.loadHTMLString(text!, baseURL: nil)
}
}
// End Of Custom bottomfooter
// rate app
func rateApp()
{
UIApplication.shared.openURL(URL(string: "https://itunes.apple.com/in/app/xyz/idxyz")!)
}
// share app
func shareApp(_ shareAppText: String,shareAppUrl: String)
{
let firstActivityItem = shareAppText
let secondActivityItem = shareAppUrl
print("printing firstActivityItem \(firstActivityItem)")
print("printing secondActivityItem \(secondActivityItem)")
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [firstActivityItem, secondActivityItem], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
//share product page
func shareAppPage(_ shareAppPageSubject: String, shareAppPageURL: String)
{
print("printing shareAppPageText \(shareAppPageSubject)")
let firstActivityItem = shareAppPageSubject
let secondActivityItem : URL = URL(string: shareAppPageURL)!
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [firstActivityItem, secondActivityItem], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
//session handling
func loadFromBaseUrl()
{
viewDidLoad()
}
func checkUpdate()
{
let nsObject : AnyObject! = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as AnyObject!
let localVersion = nsObject as! String
let numberFromString = (localVersion as NSString).doubleValue
print("ios App version "+localVersion)
let UpdateUrl:NSURL = NSURL(string: "example.com?actionname=MobileAppAjaxHandler.getIOSMobileAppVersion")!
let request:NSMutableURLRequest = NSMutableURLRequest(url:UpdateUrl as URL)
let queue: OperationQueue = OperationQueue()
// Sending Asynchronous request using NSURLConnection
NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: queue, completionHandler:{(response:URLResponse?, responseData:Data?, error: Error?) -> Void in
if error != nil
{
print(error.debugDescription)
}
else
{
//Converting data to String
let responseStr = NSString(data: responseData!, encoding: String.Encoding.utf8.rawValue)
print("response of remote Ios version ========"+(responseStr! as String))
let serverVersion = responseStr! as String
let numfromstr = (serverVersion as NSString).doubleValue
if numfromstr > numberFromString
{
let updateBox = UIAlertController(title: "Update App", message: "App update is available on app store", preferredStyle: UIAlertControllerStyle.alert)
updateBox.addAction(UIAlertAction(title: "Update", style: .default, handler: { (action:UIAlertAction) in
UIApplication.shared.openURL(URL(string: "https://itunes.apple.com/in/app/xyz/idxyz")!)
}))
updateBox.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action:UIAlertAction) in
}))
self.present(updateBox, animated: true, completion: nil)
}
}
})
}
override func viewWillAppear(_ animated: Bool)
{
print("inside view WillAppear for Portrait orientation");
super.viewWillAppear(animated)
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
override var shouldAutorotate : Bool
{
print("shouldAutorotate return false");
return false
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask
{
print("supportedInterfaceOrientations");
return UIInterfaceOrientationMask.portrait
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void)
{
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_)-> Void in
completionHandler()
}))
self.present(alert, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void)
{
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_)-> Void in
completionHandler(true)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_)-> Void in
completionHandler(false)
}))
self.present(alert, animated: true, completion: nil)
}
}
我的 Xcode 版本是 9.2,这是我唯一的文件。任何小帮助将不胜感激
最佳答案
尝试使用 layout anchors 而不是 frame 对您的自定义 WKWebView 执行 autolayout。
let containerViewHeight: CGFloat = 45
webView = WKWebView()//(frame: CGRect(x:0, y: 0, width:screenWidth, height:screenHeight))
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
webView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0).isActive = true
webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -containerViewHeight).isActive = true
containerView = WKWebView()//(frame: CGRect(x:0, y: 0, width:screenWidth, height:screenHeight))
view.addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true
containerView.topAnchor.constraint(equalTo: webView.bottomAnchor, constant: 0.0).isActive = true
containerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0.0).isActive = true
为了一目了然的 safeArea 区域,我添加了下图。
关于ios - 在 iphone X 的安全区域设置 Webview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53515904/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A
我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
在Ruby中是否有Gem或安全删除文件的方法?我想避免系统上可能不存在的外部程序。“安全删除”指的是覆盖文件内容。 最佳答案 如果您使用的是*nix,一个很好的方法是使用exec/open3/open4调用shred:`shred-fxuz#{filename}`http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html检查这个类似的帖子:Writingafileshredderinpythonorruby?
我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r