2015-01-03 34 views
4

我試圖將RTF文件內容讀取到歸屬字符串,但attributedTextnil。爲什麼?RTF文件歸屬字符串

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 
    } 
} 

UPD:我改變代碼:

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不是零,並且包含來自文件屬性的文本。

+0

什麼說的'錯誤'? – Larme

+0

@Larme由於範圍沒有執行,我無法讀取錯誤。 – Shmidt

+0

不要做'如果',只要'let attributedText',然後讀'錯誤'。 – Larme

回答

4

而不是想看看如果操作工作/失敗的調試器,你會好得多編寫代碼來妥善處理失敗:

if let attributedText = NSAttributedString(fileURL: fileURL, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: &error) { 
    textView.attributedText = attributedText 
} 
else if let error = error {     
    println(error.localizedDescription) 
} 
+0

''''''可選(「操作無法完成(Cocoa error 256。)」)'''仍然崩潰。錯誤是零。 – Shmidt

+1

如果你有我上面提供的確切代碼,我不明白你給出的錯誤是非零(如果它是零,你的錯誤信息來自哪裏?),錯誤可能是零。你確定崩潰不在代碼中的其他地方嗎? –

+0

你是對的。問題是我用didSet設置文本。將代碼替換爲viewDidLoad解決了問題。 – Shmidt

0

斯威夫特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") 
+1

** Swift 4 **更新 '選項:[NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.rtf]' – selljamhere

+1

@selljamhere我更新了答案謝謝 – zombie