POI - Excel 파일 내에 이미지 추출

Programming/Java 2017.07.22 18:38 Posted by 파란크리스마스

출처 : Apache POI - the Java API for Microsoft Documents
java - Get an image and its position from excel file using Apache POI

POI로 엑셀 파일 열기

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestPoiMain {
	
	public static void main(String[] args) throws Exception {
		// 
		String fileName = "test1.xlsx";
		//
		File xlsFile = new File(fileName);
		
		Workbook workbook = null;
		try {
			if (xlsFile.exists()) {
				FileInputStream inputStream = new FileInputStream(xlsFile);
				workbook = new XSSFWorkbook(inputStream);

				System.out.println(workbook);
			}
		} finally {
			if (workbook != null)
				workbook.close();
		}
	}
}

POI로 Excel 파일 내에 이미지 추출

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestPoiMain {
	
	public static void main(String[] args) throws Exception {
		// 
		String fileName = "test1.xlsx";
		String tarDir = "c:\\test";
		//
		File xlsFile = new File(fileName);
		
		Workbook workbook = null;
		try {
			if (xlsFile.exists()) {
				FileInputStream inputStream = new FileInputStream(xlsFile);
				workbook = new XSSFWorkbook(inputStream);
				
				XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0);
				XSSFDrawing drawing = sheet.createDrawingPatriarch(); // I know it is ugly, actually you get the actual instance here
				for (XSSFShape shape : drawing.getShapes()) {
					if (shape instanceof XSSFPicture) {
						XSSFPicture picture = (XSSFPicture) shape;
						
						if (picture.getPictureData()==null) {
							System.out.println("사진 Path 사용");
							continue;
						}
						XSSFPictureData xssfPictureData = picture.getPictureData();
						ClientAnchor anchor = picture.getPreferredSize();
						int row1 = anchor.getRow1();
						int row2 = anchor.getRow2();
						int col1 = anchor.getCol1();
						int col2 = anchor.getCol2();
						System.out.println("Row1: " + row1 + " Row2: " + row2);
						System.out.println("Column1: " + col1 + " Column2: " + col2);
						// Saving the file
						String ext = xssfPictureData.suggestFileExtension();
						byte[] data = xssfPictureData.getData();
						
						FileOutputStream out = new FileOutputStream(String.format("%s\\%s_%d_%d.%s", tarDir, sheet.getSheetName(), row1, col1, ext));
						out.write(data);
						out.close();
					}
				}
			}
		} finally {
			if (workbook != null)
				workbook.close();
		}
	}
}
저작자 표시
신고

Spring MVC - ObjectMapper이용 Object to JSON 반환

Programming/Java 2017.07.16 17:13 Posted by 파란크리스마스

출처 : How to convert Java object to / from JSON (Jackson) - Mkyong
스프링3(Spring3) - @ResponseBody + jackson을 이용하여 심플하게 구현하기
Chapter16. 스프링 MVC로 REST API 사용하기 · Spring Study Group
Spring에서 JSON과 연동방법 - 와이케이의 마구잡이 - GitHub Pages
[ERROR:] cvc-complex-type.2.1: Element 'mvc ... - kkan's - Tistory

pom.xml 내용 추가

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

VO 객체

package com.myhome.dto;

import java.util.ArrayList;

public class JSONTest {
	
	private int id;
	private String txt;
	private ArrayList<String> list;
	private String[] arr;

	public String[] getArr() {
		return arr;
	}

	public void setArr(String[] arr) {
		this.arr = arr;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}
}

Controller

package com.myhome.ui;

import java.io.IOException;
import java.util.ArrayList;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myhome.dto.JSONTest;

@Controller
public class HelloController {

	@RequestMapping(value = "/jsonTest.do", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody String jsonTest() throws JsonGenerationException, JsonMappingException, IOException {
		
		// 가상의 배열및 리스트에 데이터 add
		ArrayList<String> arraylist = new ArrayList<String>();
		arraylist.add("a");
		arraylist.add("b");
		String[] array = { "a", "b", "c" };

		// VO객체에 SET한후 vo객체자체를 return
		JSONTest test = new JSONTest();
		test.setId(1);
		test.setTxt("textTxt");
		test.setList(arraylist);
		test.setArr(array);
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonString = mapper.writeValueAsString(test);
		
		return jsonString;
	}
}

실행

저작자 표시
신고

Spring MVC - Object to JSON 반환

Programming/Java 2017.07.15 20:12 Posted by 파란크리스마스

출처 : 스프링3(Spring3) - @ResponseBody + jackson을 이용하여 심플하게 구현하기
Chapter16. 스프링 MVC로 REST API 사용하기 · Spring Study Group
Spring에서 JSON과 연동방법 - 와이케이의 마구잡이 - GitHub Pages
[ERROR:] cvc-complex-type.2.1: Element 'mvc ... - kkan's - Tistory

pom.xml 내용 추가

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.6.3</version>
		</dependency>

***-servlet.xml 내용 추가

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/aop       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                           http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                           http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-2.5.xsd
                           http://www.springframework.org/schema/jee       http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                           http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                           http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                           http://www.springframework.org/schema/security  http://www.springframework.org/schema/security/spring-security-2.0.xsd">

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/html;charset=UTF-8</value>
						<value>application/json;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>

VO 객체

package com.myhome.dto;

import java.util.ArrayList;

public class JSONTest {
	
	private int id;
	private String txt;
	private ArrayList<String> list;
	private String[] arr;

	public String[] getArr() {
		return arr;
	}

	public void setArr(String[] arr) {
		this.arr = arr;
	}

	public ArrayList<String> getList() {
		return list;
	}

	public void setList(ArrayList<String> list) {
		this.list = list;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTxt() {
		return txt;
	}

	public void setTxt(String txt) {
		this.txt = txt;
	}
}

Controller

package com.myhome.ui;

import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myhome.dto.JSONTest;

@Controller
public class HelloController {

	@RequestMapping(value = "/jsonTest.do", method = RequestMethod.GET, produces = "application/json")
	public @ResponseBody JSONTest jsonTest() {
		
		// 가상의 배열및 리스트에 데이터 add
		ArrayList<String> arraylist = new ArrayList<String>();
		arraylist.add("a");
		arraylist.add("b");
		String[] array = { "a", "b", "c" };

		// VO객체에 SET한후 vo객체자체를 return
		JSONTest test = new JSONTest();
		test.setId(1);
		test.setTxt("textTxt");
		test.setList(arraylist);
		test.setArr(array);
		return test;
	}
}

실행

저작자 표시
신고

Node.js - Windows에 설치

Programming/Node.js 2017.07.09 19:13 Posted by 파란크리스마스

출처 : [nodejs] 윈도우에서 node.js 설치 및 실행하기 - 워크식스 블로그

PATH에 추가

C:\server\node-v6.11.2-win-x64

Hello world

C:\> node
>
(To exit, press ^C again or type .exit)
> console.log('hello world!')
hello world!
undefined

웹서비스

// 모듈을 추출합니다.
var http = require('http');

// 웹 서버를 만들고 실행합니다.
http.createServer(function (request, response) {
  response.writeHead(200, { 'Content-Type': 'text/html' });
  response.end('<h1>Hello World!</h1>');
}).listen(80, function () {
  console.log('Server running at http://127.0.0.1/');
});

실행

C:\> node http_test.js
저작자 표시
신고

Swift - 외부라이브러리 사용

Programming/Swift 2017.07.01 17:15 Posted by 파란크리스마스

Swift - 외부라이브러리 사용

출처 : DLRadioButton
Seorenn SIGSEGV: Swift 프로젝트에서 Objective-C 코드를 함께 사용하기

외부라이브러리 파일 추가

파일 추가 옵션 선택

브릿지 헤더 파일 생성

브릿지 헤더 파일 설정

자동으로 설정되지만 설정이 되지 않았을 경우 아래와 같이 설정 필요

Button Type 변경

Button Type 변경 전

Button Type 변경 후

Button 라디오버튼의 경우 그룹으로 묶기

Button 라디오버튼 하나의 이벤트 생성


Button 라디오버튼 이벤트 구현

    @IBAction func optionClicked(_ sender: DLRadioButton) {
        print(sender.currentTitle!)

        if (sender == radio1) { // (sender.currentTitle == "석굴암") {
            imageView.image = image1
        } else if (sender.currentTitle == "남대문") {
            imageView.image = image2
        } else if (sender.currentTitle == "독립기념관") {
            imageView.image = image3
        }
    }
저작자 표시
신고

Swift - Layout 가운데 정렬

Programming/Swift 2017.07.01 10:07 Posted by 파란크리스마스

출처 : IOS 오토레이아웃(AUTOLAYOUT) 사용패턴1 화면 가운데 버튼 배치하기

Top, Width, Height 설정

가운데 정렬


상대 좌표 배치

수평 상대 좌표 설정

수직 상대 좌표 배치

멀티터치 옵션 설정

저작자 표시
신고

Swift - Free Draw

Programming/Swift 2017.07.01 09:46 Posted by 파란크리스마스

출처 : Freehand drawing on iOS in Swift - Ilya Puchka


    override func touchesBegan(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesBegan"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lastPoint = touch.location(in: drawImageView)
        }
    }
    
    override func touchesMoved(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesMoved"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
            
            lineWidth = CGFloat(Int(textLineWidth.text!)!);
            
            UIGraphicsBeginImageContext(drawImageView.frame.size)
            if let context = UIGraphicsGetCurrentContext() {
                context.setLineWidth(lineWidth)
                context.setStrokeColor(lineColor)
                context.setLineCap(CGLineCap.round)
                
                drawImageView.image?.draw(in: CGRect(origin: CGPoint(x : 0, y : 0), size: drawImageView.frame.size))
                
                context.move(to: lastPoint)
                let currentPoint = touch.location(in: drawImageView)
                context.addLine(to : currentPoint)
                context.strokePath()
                
                drawImageView.image = UIGraphicsGetImageFromCurrentImageContext()
                
                lastPoint = currentPoint
            }
            UIGraphicsEndImageContext()
        }
    }

    override func touchesEnded(_ touches: Set<uitouch>, with event: UIEvent?) {
        if let touch = touches.first {
            messageLabel.text = "touchesEnded"
            tapCountLabel.text = String(touch.tapCount)
            touchCountLabel.text = String(touches.count)
        }
    }


저작자 표시
신고

Swift - 예외처리

Programming/Swift 2017.07.01 09:28 Posted by 파란크리스마스

출처 : Swift 에러 (Error) 처리, 예외 상황 다루기 (try, throws, defer 등) : 네이버 ...

    enum ParseError : Error {
        case OverSize
        case UnderSize
        case InvalidFormat(value : String)
        case InvalidData(value : String)
    }

예외발생

    func parseTime(timeString : NSString) throws -> Time {
        
        var retTime = Time(hour : 0, min : 0, sec : 0)
        
        guard timeString.length == 8 else {
            if timeString.length > 8 {
                throw ParseError.OverSize
            } else {
                throw ParseError.UnderSize
            }
        }
        
        if let hour = Int(timeString.substring(to: 2)) {
            print(hour)
            guard hour >= 0 && hour < 24 else {
                throw ParseError.InvalidFormat(value: "시간")
            }
            
            retTime.hour = hour
        } else {
            throw ParseError.InvalidFormat(value: "시간")
        }
        
        if let min = Int(timeString.substring(with : NSRange(location : 3, length : 2))) {
            print(min)
            guard min >= 0 && min < 60 else {
                throw ParseError.InvalidFormat(value: "분")
            }
            
            retTime.min = min
        } else {
            throw ParseError.InvalidFormat(value: "분")
        }
        
        if let sec = Int(timeString.substring(from : 6)) {
            print(sec)
            guard sec >= 0 && sec < 60 else {
                throw ParseError.InvalidFormat(value: "초")
            }
            
            retTime.sec = sec
        } else {
            throw ParseError.InvalidFormat(value: "초")
        }
        
        return retTime		
    }

예외처리

    func getPartTime(timeString : NSString, type : String) {
        do {
            let time = try parseTime(timeString : timeString)
            
            switch type {
            case "hour":
                print("\(time.hour)시")
            case "min":
                print("\(time.min)분")
            case "sec":
                print("\(time.sec)초")
            default:
                print("입력값 배당 시간 정보 없음")
            }
            
        }
        catch ParseError.OverSize {
            print("입력 문자열이 깁니다.")
        }
        catch ParseError.UnderSize {
            print("입력 문자열이 짧습니다.")
        }
        catch ParseError.InvalidData(let part) {
            print("입력값의 \(part)에 해당하는 형식 오류")
        }
        catch ParseError.InvalidFormat(let part) {
            print("입력값의 \(part)에 해당하는 값 오류")
        }
        catch {
            print("알 수 없는 오류")
        }
    }
저작자 표시
신고

Spring - 파일 업로드

Programming/Java 2017.06.18 10:39 Posted by 파란크리스마스

출처 : [Spring, Tomcat] Could not parse multipart servlet request Unable to process parts as no multi-part configuration has been provided 해결 [소림사의 홍반장!]
[Apache/Tomcat] Context.xml 수정을 통한 문제 해결 - Cache, CSRF(Upload) [PostIT]
[Spring] Multipart를 사용한 페이지에서 Filter 적용하기 : 네이버 블로그

pom.xml

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

MultipartFilter 적용(web.xml)

	<!-- MultipartFilter 적용 -->
	<filter>
		<filter-name>MultipartFilter</filter-name>
		<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>MultipartFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

MultipartResolver 등록 (spring bean 등록)

	<!--  이미지 드래그 앤 드롭 업로드 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- max upload size in bytes -->
		<property name="maxUploadSize" value="209715200" /> <!-- 20MB -->
		<!-- max size of file in memory (in bytes) -->
		<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
	</bean>

allowCasualMultipartParsing 설정 (context.xml)

방법1 %TOMCAT%/conf/context.xml - Tomcat 전체 적용

<Context allowCasualMultipartParsing="true">

	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Default set of monitored resources. If one of these changes, the -->
	<!-- web application will be reloaded. -->
	<WatchedResource>WEB-INF/web.xml</WatchedResource>
	<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

	<!-- Uncomment this to disable session persistence across Tomcat restarts -->
	<!-- <Manager pathname="" /> -->

	<!-- 케시문제 해결 -->
	<Resources cachingAllowed="true" cacheMaxSize="100000"></Resources>

</Context>

방법2 WebContent\META-INF\context.xml - Eclipse 사용시 프로젝트에 적용

<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
</Context>

form의 enctype

<form action="<c:url value="/insertCompleteForProblem.do"/>" method="post" enctype="multipart/form-data">
	    <tr>
	        <th scope="row">file</th>
	        <td><input type="file" size="20"  name="file1"></td>
	    </tr>

controller

	@RequestMapping(value = "/insertCompleteForProblem.do", method = RequestMethod.POST, headers = ("content-type=multipart/*"))
	public String joinComplete(
			@RequestParam("seq") int seq, 
			@RequestParam("quiz_name") String quiz_name, 
			@RequestParam("user_id") String user_id, 
			@RequestParam("price") String price,
			@RequestParam(value = "file1", required = false) MultipartFile mediaFile, 
			HttpServletRequest request, 
			ModelMap modelMap) throws Exception 
	{

		System.out.println("seq : " + seq);
		System.out.println("quiz_name : " + quiz_name);
		System.out.println("user_id : " + user_id);
		System.out.println("price : " + price);

		if (mediaFile.isEmpty() == false) {
			System.out.println("------------- file start -------------");
			System.out.println("name : " + mediaFile.getName());
			System.out.println("filename : " + mediaFile.getOriginalFilename());
			System.out.println("size : " + mediaFile.getSize());
			System.out.println("-------------- file end --------------\n");

			String originalFilename = mediaFile.getOriginalFilename(); // 파일명

			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);

			UUID uuid = UUID.randomUUID();
			String targetFilename = uuid.toString() + "." + fileExt.toLowerCase();

			File file = new File(getDestinationLocation() + targetFilename);
			mediaFile.transferTo(file);
		}

		return "redirect:/main.do";
	}

	private String getDestinationLocation() {
		// return "/home/hosting_users/terecal/www/intel_images/";
		return "c:\\test\\";
	}


저작자 표시
신고

Swift - UITableView

Programming/Swift 2017.06.17 15:25 Posted by 파란크리스마스

출처 : [IOS/Swift] Custom TableView Cell 만들기 - 코딩하는 빵 - Tistory

//
//  ViewController.swift
//  TableView2
//
//  Created by bluesanta on 2017. 6. 10..
//  Copyright © 2017년 bluesanta. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var toDoArray = ["영화보기", "야구보기", "수영하기"]

    @IBOutlet weak var toDoTableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.toDoTableView.dataSource = self
        self.toDoTableView.delegate = self;
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return toDoArray.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "toDoCell", for:indexPath)
        cell.textLabel?.text = toDoArray[indexPath.row]
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 선택 이벤트
    }
}

Custom Cell

Custom Cell Class 생성 및 지정

Custom Cell 사용

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tvCell", for:indexPath) as! MovieTableViewCell
        //cell.textLabel?.text = movieArray[indexPath.row].title
        cell.thumbnailImageView.image = nil
        cell.titleLabel.text = movieArray[indexPath.row].title
        cell.genreLabel.text = movieArray[indexPath.row].genre
        cell.ratingLabel.text = movieArray[indexPath.row].ratingAverage
        
        /*
        if let titleLabel =  cell.viewWithTag(11) as? UIImageView {
            titleLabel.text = movieArray[indexPath.row].title
        }
        */
    
        return cell
    }

TableView 갱신

           // 메일 쓰레드에서 화면 갱신
            DispatchQueue.main.async {
                self.tvMovie.reloadData()
            }

테이블 상단 공백 제거

- Adjust Scroll View Inserts 체크 제거

저작자 표시
신고

Swift - JSON 파싱

Programming/Swift 2017.06.17 12:43 Posted by 파란크리스마스

json 파싱

        let jsonString = "{ \"name\":\"test\", \"age\":30 }"
        if let data = jsonString.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                    
                    print(json["name"] ?? "")
                    print(json["age"] ?? 0)
                }
            } catch {
                print("JSON 파싱 에러")
            }
        }

원격호출 json 파싱

let urlString = "http://115.68.183.178:2029/hoppin/movies?order=releasedateasc&count=10&page=1&version=1&genreId="
        guard let url = URL(string: urlString) else { return }
        
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
            guard let data = data,
            let httpRes = response as? HTTPURLResponse, httpRes.statusCode == 200 else {
                return
            }

            if let error = error {
                print(error.localizedDescription)
                return;
            }
            
            do {
                if let jsonDic = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                    print(jsonDic)
                    
                    guard let totalInfo = jsonDic["hoppin"] as? [String : AnyObject],
                        let totalCount = totalInfo["totalCount"] as? String,
                        let movies = totalInfo["movies"] as? [String :AnyObject],
                        let movieArray = movies["movie"] as? [[String:AnyObject]] else {return}
                    
                    print(totalCount)
                    print(movies)
    
                    for info in movieArray {
                        print(info["title"] ?? "")
                        print(info["thumbnailImage"] ?? "")
                        
                        let movieInfo = MovieInfo(title : info["title"] as? String,
                            thumbnailUrl : info["thumbnailImage"] as? String,
                            genre : info["genreNames"] as? String,
                            ratingAverage : info["ratingAverage"] as? String)
                        self.movieArray.append(movieInfo)
                    }
                    
                    
                }
            } catch {
                print("JSON 파상 에러")
            }
            
            print("JSON 파싱 완료")
            
            // 메일 쓰레드에서 화면 갱신
            DispatchQueue.main.async {
                self.tvMovie.reloadData()
            }
        })
        
        print("JSON 파싱 시작")
        task.resume()

json 파싱 함수로 구현

    func parseJSONString(jsonString : String) -> [String:AnyObject]? {
        guard let data = jsonString.data(using: .utf8) else {
            return nil
        }
        
        do {
            if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] {
                print(json);
                return json
            }
        } catch {
            print("JSON 파싱 에러")
        }

        return nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let jsonString = "{ \"name\":\"test\", \"age\":30 }"
        if let jsonDic = self.parseJSONString(jsonString: jsonString) {
            print(jsonDic["name"] ?? "")
            print(jsonDic["age"] ?? 0)
        }
    }
저작자 표시
신고

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

Programming/Swift 2017.06.17 11:19 Posted by 파란크리스마스

출처 : [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.

저작자 표시
신고


 

티스토리 툴바