2015-09-25 62 views
0

我有一個UIView,一旦按下按鈕,就會從服務器更新。Swift dispatch_async在iOS通知之前不更新UIView

UIView更新發生在dispatch_async()內。通過調試,我可以看到服務器響應已經收到,並且新的子視圖被創建並應用於UIView。

但是,視圖保持不變直到發生另一個iOS通知(例如設備收到電子郵件)。只要顯示通知標題,UIView就會刷新並顯示來自服務器的圖像。

我錯過了什麼?如何在添加新子視圖後立即更新UIView?

注意:我已經在dispatch_async()之內和之外嘗試了以下內容,並且嘗試在初始更改發生後沒有運氣的情況下在同一隊列上調用它們。

  • self.view.setNeedsDisplay()
  • self.view.bringSubviewToFront(視圖)
  • self.view.layoutIfNeeded()(感謝您的建議@buxik)

EDIT添加代碼(小版本更大類,僅添加相關部分):

class networkedImage: UIViewController { 
    @IBOutlet var viewArea: UIView = UIView() 
    let originalWidth: CGFloat = 200 
    let originalHeight: CGFloat = 100 
    let imageURL: NSURL = NSURL(string: "www.example.com/image.jpg")! 

    func updateViewArea() { 
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { 
     dispatch_async(dispatch_get_main_queue()) { 
      self.viewArea.subviews.forEach({ $0.removeFromSuperview() }) 

     let newImageView = UIImageView(frame: CGRectMake(0, 0, self.originalWidth, self.originalHeight)) 
     let data = NSData(contentsOfURL: self.imageURL) 
     if data != nil { 
     let image = UIImage(data: data!) 
     if image != nil { 
      newImageView.image = image 

      self.viewArea.addSubview(newImageView) 
      self.viewArea.bringSubviewToFront(newImageView) 
      self.viewArea.setNeedsDisplay() 
     } 

     NSNotificationCenter.defaultCenter().addObserverForName("NotificationIdentifier", object: nil, queue: nil, usingBlock: { 
     [unowned self] note in 
     print("I thought this might work, it didn't.") 
     }) 
     } 
    } 
    } 
    } 
} 
+0

也許self.view.layoutIfNeeded() – buxik

+0

@buxik沒有運氣,謝謝你的建議。 – Tr0yJ

+1

你在主隊列上進行更新嗎? dispatch_async(dispatch_get_main_queue()) –

回答

0

要解決我在updateViewArea(底部增加了一個觀察員viewDidLoad中()

 NSNotificationCenter.defaultCenter().addObserverForName("imageReadyNotification", object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { 
     [unowned self] note in 
     self.updateViewArea() 
     }) 

然後)這個問題我張貼通知

   if self.newImage == true { 
       NSNotificationCenter.defaultCenter().postNotificationName("imageReadyNotification", object: nil, userInfo: nil) 
      } 

if條件是要確保通知不不斷髮射。我不知道爲什麼調用這個函數兩次有效,但它確實如此。