我正在尝试将RTF文件内容读取为属性字符串,但attributedText
为nil
。为什么呢?
if let fileURL = NSBundle.mainBundle().URLForResource(filename, withExtension: "rtf") {
var error: NSError?
if let attributedText = NSAttributedString(fileURL: fileURL, options: [NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType], documentAttributes: nil, error: &error){
textView.attributedText = attributedText
}
}
更新:我将代码更改为:
if let fileURL = NSBundle.mainBundle().URLForResource(filename, withExtension: "rtf") {
var error: NSError?
let attributedText = NSAttributedString(fileURL: fileURL, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: &error)
println(error?.localizedDescription)
textView.attributedText = attributedText
}
现在textView.attributedText = attributedText
发生了崩溃:fatal error: unexpectedly found nil while unwrapping an Optional value
。我在调试器中看到attributedText
不是nil,并且包含带有来自file的属性的文本。
答案 0 :(得分:6)
不是在调试器中查看操作是否有效/失败,而是编写代码来更好地处理失败:
if let attributedText = NSAttributedString(fileURL: fileURL, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: &error) {
textView.attributedText = attributedText
}
else if let error = error {
println(error.localizedDescription)
}
Swift 4
do {
let attributedString = try NSAttributedString(url: fileURL, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
print("\(error.localizedDescription)")
}
答案 1 :(得分:1)
Swift 4 @available(iOS 7.0,*)
func loadRTF(from resource: String) -> NSAttributedString? {
guard let url = Bundle.main.url(forResource: resource, withExtension: "rtf") else { return nil }
guard let data = try? Data(contentsOf: url) else { return nil }
return try? NSAttributedString(data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf],
documentAttributes: nil)
}
用法:
textView.attributedText = loadRTF(from: "FILE_HERE_WITHOUT_RTF")