我有一个基于文档的 iOS 应用程序,当它第一次打开文档时,主视图 Controller 调用 UIDocument.open。
document.open { success in
if success { ... set up UI ... }
else { ??? }
}
这里的问题是,如果 success 为 false,我将无法访问该错误。通常,Apple 的 API 会在这些情况下将可选的 Error 参数传递给回调,但由于某些原因,它们不会在这里。
我发现这个方法可以在我的应用程序的 UIDocument 子类中覆盖:
override func handleError(_ error: Error, userInteractionPermitted: Bool) {
现在在该方法中我遇到了错误,但我无法轻松访问名为document.open 的 View Controller ,我需要提供类似用于显示错误消息的 UIAlertController。此 handleError 方法也在非主线程上调用。
看来我需要通过在实例或全局变量中传递信息来进行协调。因为这看起来比 Apple 的通常设计更尴尬——我希望 Error 在 open 的完成处理程序中可用,我想我可能会遗漏一些东西。
是否有另一种推荐的方法来获取错误对象并向用户显示消息?
最佳答案
罗布
如果你真的想变得“敏捷”,你可以实现一个闭包来做到这一点,而不需要静态/全局变量。
我将从定义一个枚举开始,该枚举对 UIDocument 的 API 调用的成功和失败案例进行建模。通用 Result 枚举是执行此操作的一种非常常见的方法。
enum Result<T> {
case failure(Error)
case success(T)
}
从那里我会在你的类中定义一个可选的闭包来处理 UIDocument.open 的结果
我会做的实现是这样的:
class DocumentManager: UIDocument {
var onAttemptedDocumentOpen: ((Result<Bool>) -> Void)?
func open(document: UIDocument){
document.open { result in
guard result else { return } // We only continue if the result is successful
// Check to make sure someone has set a function that will handle the outcome
if let onAttemptedDocumentOpen = self.onAttemptedDocumentOpen {
onAttemptedDocumentOpen(.success(result))
}
}
}
override func handleError(_ error: Error, userInteractionPermitted: Bool) {
// Check to make sure someone has set a function that will handle the outcome
if let onAttemptedDocumentOpen = self.onAttemptedDocumentOpen {
onAttemptedDocumentOpen(.failure(error))
}
}
}
然后我从任何类将使用 DocumentManager 你会做这样的事情:
class SomeOtherClassThatUsesDocumentManager {
let documentManger = DocumentManager()
let someViewController = UIViewController()
func someFunction(){
documentManger.onAttemptedDocumentOpen = { (result) in
switch result {
case .failure(let error):
DispatchQueue.main.async {
showAlert(target: self.someViewController, title: error.localizedDescription)
}
case .success(_):
// Do something
return
}
}
}
}
奖励:这是我编写的用于在某些 View Controller 上显示 UIAlertController 的静态函数
/** Easily Create, Customize, and Present an UIAlertController on a UIViewController
- Parameters:
- target: The instance of a UIViewController that you would like to present tye UIAlertController upon.
- title: The `title` for the UIAlertController.
- message: Optional `message` field for the UIAlertController. nil by default
- style: The `preferredStyle` for the UIAlertController. UIAlertControllerStyle.alert by default
- actionList: A list of `UIAlertAction`. If no action is added, `[UIAlertAction(title: "OK", style: .default, handler: nil)]` will be added.
*/
func showAlert(target: UIViewController, title: String, message: String? = nil, style: UIAlertControllerStyle = .alert, actionList: [UIAlertAction] = [UIAlertAction(title: "OK", style: .default, handler: nil)] ) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
for action in actionList {
alert.addAction(action)
}
// Check to see if the target viewController current is currently presenting a ViewController
if target.presentedViewController == nil {
target.present(alert, animated: true, completion: nil)
}
}
关于ios - 打开 UIDocument 时如何显示错误信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51548675/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack