2015-01-03 7 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는 :. 이제 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 

} 

: fatal error: unexpectedly found nil while unwrapping an Optional value가 나는 코드를 변경했습니다. 디버거에서 attributedText이 nil이 아니며 파일의 특성이있는 텍스트가 포함되어 있습니다.

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

무엇'오류를 말하는가 '? – Larme

+0

@Larme 범위가 실행되지 않아서 오류를 읽을 수 없습니다. – Shmidt

+0

'if'를하지 말고'let attributedText'를하고'error'를 읽으십시오. – Larme

답변

4

오히려 작업이 작동하는지보고보다/디버거에 실패, 당신은 적절하게 오류를 처리하는 코드를 작성 오프 더 나은 것 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") 
+0

'''선택 사항 ("작업을 완료 할 수 없습니다 (Cocoa error 256.)")'''에서 여전히 크래시가 있습니다. 오류는 nil입니다. – Shmidt

+1

정확한 코드를 입력했다면, 오류가 아닌 경우 오류가 발생하지 않는 것을 볼 수 없습니다 (오류 메시지가 어디에서오고 있습니까?). 충돌이 코드의 다른 곳에서 발생하지 않았습니까? –

+0

당신이 옳았습니다. 문제는 텍스트를 설정하기 위해 didSet을 사용하는 것이 었습니다. viewDidLoad 코드를 대체하면 문제가 해결됩니다. – Shmidt

0

스위프트 4 @available (아이폰 OS :

+1

** Swift 4 ** 업데이트 옵션 : [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.rtf]' – selljamhere

+1

@selljamhere 답변을 업데이트했습니다. 감사합니다. – zombie