2016-01-20 44 views
0

我的代码加载在TextView的本地RTF文件加载RTF,但怎么做我使其适用于位于在线如何使用URL,而不是本地

文件,因为它不工作时,我使用的URL 这里网址 - http://howtotechworld.com/rtfdoc.rtf

这里是代码

if let rtf = NSBundle.mainBundle().URLForResource("http://howtotechworld.com/rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) { 
    do { 
      let attributedString = try NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil) 
      textView.attributedText = attributedString 
      textView.editable = false 
      print(attributedString) 
    } 
    catch _ { 
      NSLog("catched a error"); 
    } 
+0

@LeoDabus对不起你什么意思我试图做到这一点上使用RTF文件服务器而不是本地文件 –

回答

-1

这工作在游乐场(显然需要比被迫展开更好的处理自选的,但你明白了吧):

import UIKit 

let url = NSURL(string: "http://thewalter.net/stef/software/rtfx/sample.rtf") 
let data = NSData(contentsOfURL: url!) 

do { 
    let options = [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType] 
    let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil) 
    print(attributedString) 
} catch { 
    NSLog("\(error)") 
} 
+0

NSData(contentsOfURL:url!)只能用于本地资源 –

+0

@LeoDabus是的,但是我提供了一个OP询问的答案。不管这是应该做什么,不是我决定的。 –

+0

我提供的信息OP需要不使用它 –

1

你应该异步下载您的RTF数据,并使用NSAttributedString初始化器init(data: NSData, options: [String : AnyObject], documentAttributes dict: AutoreleasingUnsafeMutablePointer<NSDictionary?>) throws加载数据完成后:

// your web link 
let rtfLink = "http://www.aliectronics.com.au/thefournobletruths.rtf" 
// make sure your link is valid NSURL using guard 
guard let rtfURL = NSURL(string: rtfLink) else { return } 
// creata a data task for your url 
NSURLSession.sharedSession().dataTaskWithURL(rtfURL) { 
    (data, response, error) in 
    // use guard to make sure you get a valid response from the server and your data it is not nil and you got no errors otherwise return 
    guard 
     let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, 
     let data = data where error == nil 
    else { return } 
    // you need to use dispatch async to update the UI 
    dispatch_async(dispatch_get_main_queue(), {() -> Void in 
     // NSAttributedString data initialiser throws an error so you need to implement Swift2 Do Try Catch error handling 
     do { 
      let attributedString = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType], documentAttributes: nil) 
      textView.attributedText = attributedString 
      textView.editable = false 
      print("attributedString=====start") 
      print(attributedString) 
      print("attributedString=====end") 
     } catch let error as NSError { 
      print(error.localizedDescription) 
     } 
    }) 
}.resume() 
相关问题