2017-01-08 14 views
0

ゆっくりとプルダウンして更新すると、新しいコンテンツが正しい順序で入れられなくなります。UIRefreshControlが正しい順序で読み込まれない

また、リフレッシュをプルするときにスタックするトリガーはエラーを起こさず、新しいセルを3つのセルの下にロードします。

import UIKit 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

@IBOutlet weak var tableview: UITableView! 

var url: String = "http://www.test.com/?json=get_recent_posts" 

//var url: String = "http://www.test.com/wp-json/wp/v2/posts" 

var refreshControl: UIRefreshControl = UIRefreshControl() 

var posts: [Post]? = [] 


// Navigation 
override func viewDidAppear(_ animated: Bool) { 
    let nav = self.navigationController?.navigationBar 
    nav?.barStyle = UIBarStyle.black 
    self.navigationController?.navigationBar.barTintColor = UIColor.white 

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) 
    imageView.contentMode = .scaleAspectFit 
    let image = UIImage(named: "logo") 
    imageView.image = image 
    navigationItem.titleView = imageView 

} 



override func viewDidLoad() { 
    super.viewDidLoad() 

    func stringFromHTML(string: String?) -> NSAttributedString? 
    { 


     do { 
      let data = string?.data(using: String.Encoding.utf8, allowLossyConversion: true) 
      if let d = data { 
       let str = try NSAttributedString(data: d, 
               options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
               documentAttributes: nil) 
       return str 
      } 
     } catch { 
     } 
     return nil 
    } 



    fetchPosts() 
    // Refresh 

    refreshControl = UIRefreshControl() 
    refreshControl.attributedTitle = NSAttributedString(string: "Refresh") 
    refreshControl.addTarget(self, action: #selector(refresh), for: UIControlEvents.valueChanged) 
    tableview.addSubview(refreshControl) // not required when using UITableViewController 
    tableview.sendSubview(toBack: refreshControl) 
    refresh() 

} 

func refresh() { 
    //print("Refresh table") 
    fetchPosts() 
} 

func fetchPosts() { 
    if self.url == "" { 
     // print("no posts") 
     DispatchQueue.main.async { 

      if (self.refreshControl.isRefreshing) { 
       self.refreshControl.endRefreshing() 
      } 

      self.tableview.reloadData() 

      UIApplication.shared.isNetworkActivityIndicatorVisible = false 
     } 
     return 
    } 

    let urlRequest = URLRequest(url: URL(string: self.url)!) 

    let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in 

     if error != nil { 
      print(error!) 
      return 
     } 

     do { 
      let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject] 

      if let postsFromJson = json["posts"] as? [[String:AnyObject]] 
      { 
       for post_json in postsFromJson { 
        let post = Post() 
        if let title = post_json["title"] as? String{ 
         post.title = title 

        } 
        if let attachments = post_json["attachments"] as? [[String: AnyObject]] { 
         if let attachment = attachments[0] as? [String: AnyObject] { 
          if let imageUrl = attachment["url"] as? String { 
           post.imageUrl = imageUrl 
          } 
         } 
        } 
        if let content = post_json["content"] as? String { 
         post.content = content 
        } 


       self.posts?.append(post) 
      } 

       DispatchQueue.main.async { 
        self.tableview.reloadData() 
       } 
     } 
     } catch let error { 
      print(error) 
     } 
    } 

    task.resume() 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "postsCell", for: indexPath) as! PostsCell 

    cell.title.text = self.posts?[indexPath.row].title 
    cell.imgView.downloadImage(from:(self.posts?[indexPath.row].imageUrl)!) 

    return cell 
} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return self.posts?.count ?? 0 
} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if (segue.identifier == "showDetail") { 
      let DVC = segue.destination as! DetailViewController 
      if let indexpath = self.tableview.indexPathForSelectedRow { 
       let title = self.posts?[indexpath.row].title 
       DVC.title_text = title 
       DVC.img_url = self.posts?[indexpath.row].imageUrl 
       DVC.content_text = self.posts?[indexpath.row].content 
      } 
     } 
    } 

    override func viewWillDisappear(_ animated: Bool) { 
     super.viewWillDisappear(animated) 
     self.tableview.reloadData() 
    } 

} 


extension UIImageView { 

    func downloadImage(from url: String){ 
     let encoded_url = url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) 
     let urlRequest = URLRequest(url: URL(string: encoded_url!)!) 

     let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in 
      if error != nil { 
       print(error!) 
       return 
      } 

      DispatchQueue.main.sync { 
       self.image = UIImage(data: data!) 
      } 
     } 
     task.resume() 
    } 
} 
+0

@DlonsMa、あなたはtableViewがセルを挿入した後、まだrefreshControlの更新を意味しますか? – aircraft

答えて

0

UIRefreshControlはあなたのデータの表示順序とは関係ありません、あなたのテーブルビューは0-nからのセクションと行をレンダリングします - データが(配列などを設定)どこから来るか、これまでにする必要がありますソートロジックが適用されています。

+0

私はfunc tableViewで自分のコードをリフレッシュしています...だから私は私のミスがどこにあるか見てみましょう – DInosMa

関連する問題