티스토리 뷰

Programming/Swift

Swift - OpenAPI 사용하기(XMLParser 사용)

파란크리스마스 2017. 6. 17. 11:19
728x90

출처 : [iOS/Swift] XML 파싱하기 :: 고무망치

OPEN API 호출 및 XML 파싱

class TableViewController: UITableViewController, XMLParserDelegate {

    var xmlParser = XMLParser()
    
    var currentElement = ""                // 현재 Element
    var movieItems = [[String : String]]() // 영화 item Dictional Array
    var movieItem = [String: String]()     // 영화 item Dictionary
    
    var pubTitle = "" // 영화 제목
    var contents = "" // 영화 내용
    
    func requestMovieInfo() {
        // OPEN API 주소
        let url = "http://api.koreafilm.or.kr/openapi-data2/service/api105/getOpenDataList"
        
        guard let xmlParser = XMLParser(contentsOf: URL(string: url)!) else { return }
        
        xmlParser.delegate = self;
        xmlParser.parse()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()   
        requestMovieInfo()
    }
    
    // XMLParserDelegate 함수
    // XML 파서가 시작 테그를 만나면 호출됨
    public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:])
    {
        currentElement = elementName
        if (elementName == "item") {
            movieItem = [String : String]()
            pubTitle = ""
            contents = ""
        }
    }
    
    // XML 파서가 종료 테그를 만나면 호출됨
    public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
    {
        if (elementName == "item") {
            movieItem["title"] = pubTitle;
            movieItem["contents"] = contents;
            
            movieItems.append(movieItem)
        }
    }
    
    // 현재 테그에 담겨있는 문자열 전달
    public func parser(_ parser: XMLParser, foundCharacters string: String)
    {
        if (currentElement == "contents") {
            contents = string
        } else if (currentElement == "pubtitle") {
            pubTitle = string
        }
    }

스토리 보드에서 초기 뷰컨트롤러 지정하기

is initial view controller 체크 박스 선택

XML 결과 보여주기

withIdentifier 설정

코드

    // 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 self.movieItems.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "movieCell", for: indexPath)
     
        // Configure the cell...
        cell.textLabel?.text = movieItems[indexPath.row]["title"]
     
        return cell
    }

HTTP 접속 오류 해결 하기

오류 메시지 : App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함