개발자 코드(Code)/Swfit

IOS) Scrapy + Kanna_04 (기능설명 scrapy 로 가져온 데이터 + 원하는 년도 영화 100 리스트 scrapy + 원하는 영화 링크 주소 연결)

Chain X 2020. 9. 1. 23:55
728x90
반응형

012
기능설명 scrapy 로 가져온 데이터 + 원하는 년도 영화 100 리스트 scrapy + 원하는 영화 링크 주소 연결

 

012345
사진 순으로 따라가주세요.

//
//  TableViewController.swift
//  Kanna_04
//
//  Created by Mac on 2020/09/01.
//  Copyright © 2020 MyMac. All rights reserved.
//

/// ---------------------- 순서 1 ---------------- 밑으로 2번 3번 
 
import UIKit

class TableViewController: UITableViewController, CrawlModelProtocol {
    
    @IBOutlet var listView: UITableView!
    var feedItem: NSArray = NSArray() // 배열
    var feedItemAddress: NSArray = NSArray()
    var year: String = "" // 값이 없는 상태로 한다.
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        // 아이템 다운받은거 처리하는 것
        self.listView.delegate = self // 나한테 쓰는 거다.
        self.listView.dataSource = self
        
        let crawlModel = CrawlModel()
        crawlModel.delegate = self
        year = "2019" // 값을 넣어준다.
        self.title = "Rotten Tomatoes : \(year)" // 값을 받은 걸 바꿔줄 수 있다.
        
        crawlModel.dataCrawling(year: year)
    }
    
    func itemDownloaded(items: NSArray, itemsAddress: NSArray) {
        feedItem = items
        feedItemAddress = itemsAddress
        self.listView.reloadData() // 받아온 자료를 정리하는 것
    }

    
    // alert안에 텍스트 필드 넣기
    @IBAction func btnYear(_ sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "년도 입력", message: "순위를 보고 싶은 년도는?", preferredStyle: UIAlertController.Style.alert)
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil)
        let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {ACTION in
            if let year = alert.textFields?.first?.text{
                self.title = "Rotten Tomatoes : \(year)"
                let crawlModel = CrawlModel()
                crawlModel.delegate = self
                crawlModel.dataCrawling(year: year)
            }
        })
        alert.addTextField(configurationHandler: {textField in
            textField.placeholder = "년도 입력..."
        })
        alert.addAction(cancelAction)
        alert.addAction(okAction)
        
        present(alert, animated: true, completion: nil)
    }
    
    
    
    
    
    
    
    
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return feedItem.count // 넘오는 갯수는 feedItems이 알고 있다.
    }

    // tableView를 구동시키는 얘가 위에있는 reloadData() 이다.
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)

        // Configure the cell...
        let item: String = feedItem[indexPath.row] as! String
        cell.textLabel?.text = "\(item)"
        return cell
    }
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            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 to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation
    // prepare 부분
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "sgHTML" {
            let cell = sender as!  UITableViewCell
            let indexPath = self.listView.indexPath(for: cell)
            let detailView = segue.destination as! ViewController
            detailView.receiveItem = feedItemAddress[(indexPath! as NSIndexPath).row] as! String
        }
    }
    

}

 

//
//  CrawlModel.swift
//  Kanna_04
//
//  Created by Mac on 2020/09/01.
//  Copyright © 2020 MyMac. All rights reserved.
//

import Foundation
import Kanna

protocol CrawlModelProtocol: class {
    func itemDownloaded(items: NSArray, itemsAddress: NSArray) // next step array

    
}

class CrawlModel: NSObject{
    var delegate: CrawlModelProtocol!
    
    func dataCrawling(year: String){
        let mainURL = "https://www.rottentomatoes.com/top/bestofrt/?year=\(year)"
        let locations = NSMutableArray()
        // 영화의 주소 가져오기
        let locationsAddress = NSMutableArray()
      
        guard let main = URL(string: mainURL) else{
            print("Error \(mainURL) doesn't seem to be a valid URL.")
            return
        }
        do{
            let htmlData = try String(contentsOf: main, encoding: .utf8)
            let doc = try HTML(html: htmlData, encoding: .utf8)
            
            var count = 0
            for title in doc.xpath("//*[@id='top_movies_main']/div/table/tr/td/a"){
            let tempAddress = "https://www.rottentomatoes.com\(String(title["href"]!))"
            print(count, ":", title.text!.trimmingCharacters(in: .whitespacesAndNewlines))
            count += 1
            let countStr = String(format: "%3d", count)
            let tempStr = "\(countStr) : \(String(title.text!.trimmingCharacters(in: .whitespacesAndNewlines)))"
                locations.add(tempStr)
                locationsAddress.add(tempAddress)
            }
            print("----------------------------------------")
        }catch let error{
            print("Error: \(error)")
        }
        DispatchQueue.main.async(execute: {() -> Void in // aync로 넘긴다.
            self.delegate.itemDownloaded(items: locations, itemsAddress: locationsAddress)
        })
    }
}
​

 

//
//  ViewController.swift
//  Kanna_04
//
//  Created by Mac on 2020/09/01.
//  Copyright © 2020 MyMac. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    
    @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
    @IBOutlet weak var myWebView: WKWebView!
    
    var receiveItem = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        loadWebPage(url: receiveItem)
    }
    
    func loadWebPage(url: String){
        let myUrl = URL(string: url)
        let myRequest = URLRequest(url: myUrl!)
        myWebView.load(myRequest)
        
        myWebView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        // Observer가 Loading 중인지 확인
        if keyPath == "loading"{
            if myWebView.isLoading{
                myActivityIndicator.stopAnimating()
                myActivityIndicator.isHidden = false
            }else{
                myActivityIndicator.startAnimating()
                myActivityIndicator.isHidden = true
            }
        }
    }
    
    @IBAction func btnRefresh(_ sender: UIBarButtonItem) {
        myWebView.reload() 
    }
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
반응형