2016-01-22 80 views
0

我有一個UITextView從服務器獲取並加載文件。我如何添加一個活動指示器來顯示它正在加載?託管它的服務器有點慢。如何將活動指標添加到UITextView?

這裏是代碼:

let url = NSURL(string: "http://www.aliectronics.com.au/thefournobletruths.rtf") 
let data = NSData(contentsOfURL: url!) 

do { 
    let options = [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType] 
    let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil) 
    print(attributedString) 
    textview2.attributedText = attributedString 
    textview2.editable = false 
} catch { 
    NSLog("\(error)") 

回答

0

你不應該使用NSData contentsOfURL初始化器來同步下載數據。無法保證它會成功。您需要使用NSURLSession方法dataTaskWithURL異步下載您的數據,因爲我已經在您的最後question處向您建議。關於你的新問題,已經回答here。結合這兩個答案,你應該能夠完成你想要的。更多信息在波紋管代碼::評論

import UIKit 

class ViewController: UIViewController { 

    @IBOutlet var textview2: UITextView! 

    // declare your activityIndicator 
    let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White) 
    // you will need a new view for your activity indicator and a label for your message 
    let messageFrame = UIView() 
    let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 50)) 


    func displayActivityIndicator() { 
     strLabel.text = "Loading file" 
     strLabel.textColor = UIColor.whiteColor() 
     messageFrame.layer.cornerRadius = 15 
     messageFrame.backgroundColor = UIColor(white: 0, alpha: 0.7) 
     activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50) 
     activityIndicator.startAnimating() 
     messageFrame.addSubview(activityIndicator) 
     messageFrame.addSubview(strLabel) 
     view.addSubview(messageFrame) 
    } 

    override func viewDidAppear(animated: Bool) { 
     // set your message frame (you can also position it using textview2.frame 
     messageFrame.frame = CGRect(x: view.frame.midX - 80, y: view.frame.midY - 25 , width: 160, height: 50) 
     // call your activity indicator method 
     displayActivityIndicator() 
     // call your method to download your data asynchronously 
     getRTFDataFromLink("https://dl.dropboxusercontent.com/u/87285547/test.rtf", textview2) 
    } 

    func getRTFDataFromLink(link: String,_ textView: UITextView) { 
     // make sure your link is valid NSURL using guard 
     guard let rtfURL = NSURL(string: link) 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 

       // stop animating the activity indicator and remove the messageFrame from the view 
       self.activityIndicator.stopAnimating() 
       self.messageFrame.removeFromSuperview() 

       // NSAttributedString data initialiser throws an error so you need to implement Swift2 Do Try Catch error handling 
       do { 
        textView.attributedText = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute : NSRTFTextDocumentType], documentAttributes: nil) 
        textView.editable = false 
       } catch let error as NSError { 
        print(error.localizedDescription) 
       } 
      }) 
     }.resume() 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

} 
+0

https://www.dropbox.com/s/nt99imgsums2db8/async%20textField%20activity.zip?dl=0 –

+0

我怎麼能有出多個網址複製代碼爲每個鏈接和textview謝謝 –

+0

檢查我的編輯,你只需要添加另一個參數到textView對象,並通過它時,你調用該方法 –

0

這裏去的代碼如何在SWIFT-

var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)//choose from the indicator styles available by default 
    activityIndicator.frame = CGRectMake(0.0, 0.0, 50.0, 50.0)//set the frame of the indicator over here. 
    activityIndicator.center = view.center//where you want to place. usually we place it at the centre of our superview 
    view.addSubview(activityIndicator)//adding the indicator 
    activityIndicator.bringSubviewToFront(view) 
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true 

現在顯示簡單的激活指示,無論你想,我們作爲加 -

activityIndicator.startAnimating()//Here we start the animation 

我們通常在我們加載或撥打電話之前開始動畫從URL加載數據。

要刪除&停止動畫 -

activityIndicator.stopAnimating() 
activityIndicator.removeFromSuperview() 

希望這會爲你工作,如果你喜歡,你可以去了更多的自定義設置。有許多博客和鏈接可以參考更多自定義。