2016-12-20 2 views
0

Alamofire로 Swift 3에 내 앱을 구축하고 있습니다. JSON 데이터가 목록보기로 표시됩니다. 내용을 새로 고치는 대신 내용을 새로 고칠 때마다 목록보기를 새로 고치는 대신 항목을 목록보기의 목록 맨 아래에 추가합니다. 내 코드는 지금까지입니다, 내가 잘못 일을 할 수 있는지 모르겠어요새로 고침이 작동하지 않음

import UIKit 
import Alamofire 
import SVProgressHUD 

struct postinput { 
    let mainImage : UIImage! 
    let name : String! 
    let author : String! 
    let summary : String! 
    let content : String! 


} 


class TableViewController: UITableViewController { 

    //var activityIndicatorView: UIActivityIndicatorView! 

    var postsinput = [postinput]() 

    var refresh = UIRefreshControl() 

    var mainURL = "https://www.example.com/api" 

    typealias JSONstandard = [String : AnyObject] 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     tableView.separatorStyle = UITableViewCellSeparatorStyle.none 


     self.tableView.addSubview(refresh) 

     //;refresh.attributedTitle = NSAttributedString(string: "Refreshing...", attributes:[NSForegroundColorAttributeName : UIColor.black]) 
     refresh.backgroundColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0) 
     //refresh.tintColor = UIColor.white 

     refresh.addTarget(self, action: #selector(self.refreshData), for: UIControlEvents.valueChanged) 
     //refresh.addTarget(self, action: #selector(getter: TableViewController.refresh), for: UIControlEvents.valueChanged) 
     refresh.attributedTitle = NSAttributedString(string: "Updated: \(NSDate())") 


     //activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) 
     //tableView.backgroundView = activityIndicatorView 

     callAlamo(url: mainURL) 


    } 

    func refreshData() { 

     Alamofire.request("https://www.example.com/api").responseJSON(completionHandler: { 
      response in 
      self.parseData(JSONData: response.data!) 
      self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine 

      DispatchQueue.main.async { 
       self.tableView.reloadData() 
       self.refresh.endRefreshing() 
      } 


     }) 



    } 



    func callAlamo(url : String){ 
     //activityIndicatorView.startAnimating() 
     SVProgressHUD.show(withStatus: "Loading...") 
     SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark) 
     SVProgressHUD.setDefaultAnimationType(SVProgressHUDAnimationType.native) 
     SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black) 
     Alamofire.request(url).responseJSON(completionHandler: { 
      response in 
      self.parseData(JSONData: response.data!) 
      self.tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine 
      //self.activityIndicatorView.stopAnimating() 
      SVProgressHUD.dismiss() 


     }) 


    } 


    func parseData(JSONData : Data) { 
     do { 
      var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard 
      // print(readableJSON) 

      if let posts = readableJSON["posts"] as? [JSONstandard] { 
       for post in posts { 
        let title = post["title"] as! String 

        let author = post["author"] as! String 

        guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else { 
         return 
        } 
        let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) 
        print(str) 

        guard let dic1 = post["content"] as? [String: Any], let content = dic1["value"] as? String else { 
         return 
        } 
        let str1 = content.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) 
        print(str1) 





        //print(author) 

        if let imageUrl = post["image"] as? String { 
         let mainImageURL = URL(string: imageUrl) 
         let mainImageData = NSData(contentsOf: mainImageURL!) 
         let mainImage = UIImage(data: mainImageData as! Data) 

         postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content)) 
        } 
       } 
       DispatchQueue.main.async { 
        self.tableView.reloadData() 
       } 
      } 


     } 


     catch { 
      print(error) 
     } 


    } 


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return postsinput.count 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 

     // cell?.textLabel?.text = titles[indexPath.row] 

     let mainImageView = cell?.viewWithTag(2) as! UIImageView 

     mainImageView.image = postsinput[indexPath.row].mainImage 

     mainImageView.layer.cornerRadius = 5.0 
     mainImageView.clipsToBounds = true 

     //(cell?.viewWithTag(2) as! UIImageView).image = postsinput[indexPath.row].mainImage 

     let mainLabel = cell?.viewWithTag(1) as! UILabel 

     mainLabel.text = postsinput[indexPath.row].name 

     mainLabel.font = UIFont.boldSystemFont(ofSize: 18) 

     mainLabel.sizeToFit() 

     mainLabel.numberOfLines = 0; 

     let autLabel = cell?.viewWithTag(3) as! UILabel 

     autLabel.text = postsinput[indexPath.row].author 

     autLabel.font = UIFont(name: "Helvetica", size:16) 

     autLabel.textColor = UIColor(red: 0.8784, green: 0, blue: 0.1373, alpha: 1.0) /* #e00023 */ 

     let sumLabel = cell?.viewWithTag(4) as! UILabel 

     sumLabel.text = (postsinput[indexPath.row].summary).replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) 

     sumLabel.font = UIFont(name: "Helvetica", size:16) 

     sumLabel.textColor = UIColor(red:0.27, green:0.27, blue:0.27, alpha:1.0) 

     //let contentLabel = cell?.viewWithTag(0) as! UILabel 

     //contentLabel.text = (postsinput[indexPath.row].content).replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) 



     //(cell?.viewWithTag(3) as! UILabel).text = postsinput[indexPath.row].author 

     return cell! 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     SVProgressHUD.show() 
     let indexPath = self.tableView.indexPathForSelectedRow?.row 

     let vc = segue.destination as! nextVC 


     vc.articleImage = postsinput[indexPath!].mainImage 
     vc.articleMainTitle = postsinput[indexPath!].name 
     vc.articleContent = postsinput[indexPath!].content 
     SVProgressHUD.dismiss() 

     let backItem = UIBarButtonItem() 
     backItem.title = "Back" 
     navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed 



    } 


    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      postsinput.remove(at: indexPath.row) 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
     } 
    } 

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


} 

답변

1

여기를 새로 고침하는 작업은 목록에있는 데이터를 새로 고치고 새 항목을 추가하는 것입니다. 그래서 당신이해야 할 일은 새로 고침 할 때마다 목록에 항목을 추가하는 대신에, 서버에서 오는 새로운 목록을 tableView에 제공하는 것입니다. 배열이 이미 postsinput 인 경우 추가하기 전에 모든 항목을 제거해야합니다. 변경 사항을 수행 할 수있는 코드는 다음과 같습니다.

func parseData(JSONData : Data) { 

    postsinput.removeAll() 

    do { 

     ... 
     ... 
       if let imageUrl = post["image"] as? String { 
        let mainImageURL = URL(string: imageUrl) 
        let mainImageData = NSData(contentsOf: mainImageURL!) 
        let mainImage = UIImage(data: mainImageData as! Data) 

        postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content)) 
       } 
      } 
      DispatchQueue.main.async { 
       self.tableView.reloadData() 
      } 
     ... 
     ... 
} 
+0

이것은 문자 그대로 내 대답과 중복됩니다. 왜 그것이 받아 들여지는지 모르겠다. – JAL

5

귀하의 문제는 여기에 있습니다 :

postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary, content: content)) 

당신은 이전 데이터에 새로운 데이터를 추가 유지. 새 데이터를 추가하기 전에 이전 데이터를 완전히 지우려면 배열 postsinput에서 모든 요소를 ​​제거하기 만하면됩니다.

+0

하지만 난 어떻게 데이터가 목록보기로 얻을 것이다 제거하면 나는,이 목록보기에 모든 요소를 ​​추가하고 이해 그 라인? – Sole

+0

@ 솔 웹 요청에서 제공된 새 데이터를 추가하기 전에 현재 배열에있는 모든 요소를 ​​제거합니다. – JAL

+0

코드 예가 ​​있습니까? – Sole

관련 문제