gpt4 book ai didi

ios - 如何使用 url 而不是本地加载 rtf

转载 作者:行者123 更新时间:2023-11-30 13:46:15 25 4
gpt4 key购买 nike

我有代码可以在textview中加载本地rtf文件,但如何使其适用于在线文件

因为当我使用 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");
}

最佳答案

您应该异步下载 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()

关于ios - 如何使用 url 而不是本地加载 rtf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34893796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com