AIReport - Cell 속성 동적으로 수정하기

분류없음 2017.06.19 19:27 Posted by 파란크리스마스

AIReport - Cell 속성 동적으로 수정하기

출처 : AI Report Manual

해당 Cell에서 오른쪽 클릭 메뉴 Property Script  선택

Cell Propety Script 수정

Cell Property Script

if (user_data_list_num == user_data_list_r_count)
{
	CELL_PROPERTY_1
}

CELL_PROPERTY_1

bottomBorderWidth="1"
저작자 표시
신고
TAG AIReport

AIReport - Cell의 출력되는 변경하기

분류없음 2017.06.19 17:13 Posted by 파란크리스마스

AIReport - Cell의 출력되는 변경하기

출처 : AI Report Manual

일련번호 출력시 index가 0부터 실행되어 해당 필드의 자료형을 숫자형(int)로 설정하고 스크립트로 index + 1 하여 1부터 출력되도록 작성

UDS 설정시 필드의 자료형 숫자형(INT)으로 수정

셀 스크립트 수정

//데이터 변수 할당
sheet20_A4 = user_data_list_num;

sheet20_A4 = user_data_list_num + 1;
저작자 표시
신고
TAG AIReport

AIReport - 조건에 따라서 시트 보여짐 수정

분류없음 2017.06.19 15:12 Posted by 파란크리스마스

AIReport - 조건에 따라서 시트 보여짐 수정

출처 : AI Report Manual

파라미터 조건에 따라서 해당 시트를 숨기도록 하기

현재 Sheet 설정

[실행조건] 수정 선택

Sheet 실행조건 스크립트

if(survey_date_Param.length()<8)
{
	SHEET_PROPERTY_1
}
else
{
	return;
}
저작자 표시
신고
TAG AIReport

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.

저작자 표시
신고

Swift - 페이지 이동

Programming/Swift 2017.06.17 09:54 Posted by 파란크리스마스

출처 : 

Page View Controller

페이지 넘기기 효과

페이지 배열에 담기

    
    // lazy - 멤버가 생성되는 시점에는 메모리 할당하지 않음
    // 객체가 생성될때 초기화 함수 없이 정의만하고 객체내에서 호출시 메모리 할당
    lazy var vcArray:[UIViewController] = [self.loadVC(storyboardId: "page1VC"),
                                           self.loadVC(storyboardId: "page2VC"),
                                           self.loadVC(storyboardId: "page3VC")]
    
    // 스토리보드 ID로 ViewController 얻어오기
    func loadVC(storyboardId : String) -> UIViewController {
        return (storyboard?.instantiateViewController(withIdentifier:storyboardId))!
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        // laza 변수가 호출 되어 메모리 할당
        // static 으로 하지 않으면 객체가 만들기전에 self 함수를 호출 할 수 없지만
        // lazy 변수는 객체내에서 호출시 메모리 할당 - 미리 할당 하지 않음
        print(vcArray.count)
    }

페이지 이동 - 다음 페이지 지정

class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        guard let page1VC = vcArray.first else { return }
        self.setViewControllers([page1VC], direction: .forward, animated: true, completion: nil)
    }

    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        guard let curIndex = vcArray.index(of : viewController) else {
            return nil
        }
        
        let beforeIndex = curIndex - 1
        if beforeIndex < 0 {
            return vcArray.last
        } else {
            return vcArray[beforeIndex]
        }
    }
    
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        guard let curIndex = vcArray.index(of : viewController) else {
            return nil
        }
        
        let beforeIndex = curIndex + 1
        if beforeIndex >= vcArray.count {
            return vcArray.first
        } else {
            return vcArray[beforeIndex]
        }
    }

페이지 넘기기 효과 제거하고 페이지 이동바 표시

    // Attributes inspector > Transition Style Scroll 경우 총페이지 표시
    public func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return vcArray.count
    }
    
    // Attributes inspector > Transition Style Scroll 경우 현재 페이지 표시
    public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
        return 0
    }

페이지 이동바 숨기기

   override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        for subView in view.subviews {
            // subView가 UIScrollView 이면, subView.frame을 전체 크기(UIScreen.main.bounds)로 한다 -> 페이지 넘기는 화면이 사라짐
            if subView is UIScrollView {
                subView.frame = UIScreen.main.bounds
            }
        }
    }

Modal 페이지 띄우기

        if let modalVC = storyboard?.instantiateViewController(withIdentifier: "modalVC") {
            modalVC.modalTransitionStyle = .flipHorizontal
            present(modalVC, animated: true, completion: {
                print("show modal complete")
            })
        }

Modal 페이지 닫기

dismiss(animated: true, completion: nil)

페이지 스텍을 전부 비우고 최상위 페이지로 이동

navigationController?.popToRootViewController(animated: true)

Modal 페이지 띄우기

   @IBAction func showPage4Clicked(_ sender: UIButton) {
        
        if let page4VC = storyboard?.instantiateViewController(withIdentifier: "page4VC") {
            navigationController?.pushViewController(page4VC, animated: true)
        }
    }
    
    @IBAction func showPage7Clicked(_ sender: UIButton) {
        
        let sb = UIStoryboard(name : "main3", bundle : nil)

        let page7VC = sb.instantiateViewController(withIdentifier: "page7VC")
        
        navigationController?.pushViewController(page7VC, animated: true)
        
    }
    
    @IBAction func showPage2Clicked(_ sender: UIButton) {
        
        
        navigationController?.popViewController(animated: true)
    }

    @IBAction func showPage3Clicked(_ sender: UIButton) {
        performSegue(withIdentifier: "showPage3Segue", sender: nil)
    }
저작자 표시
신고

Swift - UIImageView.animationImages

Programming/Swift 2017.06.17 09:47 Posted by 파란크리스마스

출처 : ios - Swift - How to animate Images? - Stack Overflow

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

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var indicatorImage: UIImageView!
    
    var imageArray = [UIImage]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        for i in 1...5 {
            imageArray.append(UIImage(named: String(format : "%02d.png", i))!)
        }
        
        indicatorImage.animationImages = imageArray
        indicatorImage.animationDuration = 0.7
    }

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

    @IBAction func startClicked(_ sender: UIButton) {
        indicatorImage.startAnimating()
    }
    
    @IBAction func stopClicked(_ sender: UIButton) {
        indicatorImage.stopAnimating()
    }
    

}


저작자 표시
신고

Spring 설정 pom.xml

Programming/Java 2017.06.05 19:50 Posted by 파란크리스마스

Spring 설정 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>homepage</groupId>
	<artifactId>homepage</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<properties>
		<org.springframework-version>4.1.7.RELEASE</org.springframework-version>
		<org.springframework.security-version>4.0.1.RELEASE</org.springframework.security-version>
		<org.aspectj-version>1.8.1</org.aspectj-version>
		<org.slf4j-version>1.7.12</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- spring framework jdbc 설정 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.0.6</version>
		</dependency>
		<!-- mybatis spring -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.0.2</version>
		</dependency>

		<!-- https://stackoverflow.com/questions/1074869/find-oracle-jdbc-driver-in-maven-repository -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc</artifactId>
			<version>14</version>
			<scope>system</scope>
			<systemPath>${basedir}/libs/ojdbc6.jar</systemPath> <!-- must match file name -->
		</dependency>

	</dependencies>

</project>
저작자 표시
신고

Swift tip

Programming/Swift 2017.05.27 10:48 Posted by 파란크리스마스

Optional

출처 : 옵셔널 (Optional)

//: Playground - noun: a place where people can play

import UIKit

var email: String?
print(email) // nil

nickname = "bluexmas"
print(nickname) // Optional("bluexmas")

var str = "Hello, playground"

var name:Optional<string> = "name"
var name2:String? = "name2"

var name4:ImplicitlyUnwrappedOptional<string> = "name4";
var name3:String! = "name3"

print() name2 값이 nil 아니면 name2값 출력, name2의 값이 nil 및 경우 ?? 뒤에 있는 값 출력

if name != nil {
    print(name!)
}

if val n = name {
    print(n)
}

if let n = name {
    print(n)
}

var text1:String = "abc"
Int(test1)  // nil


var test:String = "123"
print(Int(test)! + 10)

nil 전달 함수

	var lampOn:Bool? = false
	
	func lampOnOffRemove(isOn : Bool?) {
		if let onOff = isOn {
			self.lampOn = onOff
			self.lampImageView.image = UIImage(named : onOff ? "lamp-on.png" : "lamp-off.png")
		} else {
			self.lampOn = nil
			self.lampImageView.image = UIImage(named : "lamp-remove.png")
		}
	}

	@IBAction func lampOffClicked(_ sender: AnyObject) {
		if lampOn! { // <-- 컴파일시 느낌표(!) 있어야 컴파일이 되고, 값이 nil 인 경우 런타임시 오류 발생
			//
		} else {
			//
		}
	}

WebView HTML 문자열 로딩

	@IBAction func HTMLClicked(_ sender: AnyObject) {
		let htmlString = "

HTML String

String 변수를 이용한 웹페이지

애플 홈페이지로 이동

" webView.loadHTMLString(htmlString, baseURL: nil) }

WebView HTML 파일 로딩

	func loadPageWithUrlString(urlString : String) {
		if let url = URL(string : urlString) {
			webView.loadRequest(URLRequest(url: url))
		}
	}
		
	@IBAction func fileClicked(_ sender: AnyObject) {
		if let path = Bundle.main.path(forResource: "Sample", ofType : "html") {
			loadPageWithUrlString(urlString: path)
		}
	}

WebView Delegate

class ViewController: UIViewController, UIWebViewDelegate {

	@IBOutlet weak var webView: UIWebView!
	@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
	
	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		self.webView.delegate = self
	}
	
	public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
	{
		guard let urlString = request.url?.absoluteString else {
			return true;
		}
		
		print(request.url?.absoluteString ?? "")
		
		if urlString.contains("daum.net") {
			return false;
		}
		
		return true;
	}
	
	public func webViewDidStartLoad(_ webView: UIWebView)
	{
		loadingIndicator.startAnimating()
	}
	
	public func webViewDidFinishLoad(_ webView: UIWebView)
	{
		loadingIndicator.stopAnimating()
	}
	
	public func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
	{
		print(error.localizedDescription)
		loadingIndicator.stopAnimating()
	}

포커스 이동

		// 텍스트필드 컨트롤에 포커서를 줘서 키패드가 자동으로 올라오도록 함
		self.urlTextField.becomeFirstResponder()

Objective-C main 함수

출처 : The App Life Cycle

//
//  main.m
//  study2
//
//  Created by Mac on 2017. 5. 27..
//  Copyright © 2017년 Mac. All rights reserved.
//

#import <uikit uikit.h="">
#import "AppDelegate.h"

int main(int argc, char * argv[]) {
	@autoreleasepool {
	    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
	}
}

UIImageView 확대

	@IBAction func OnBtnScaleClick(_ sender: UIButton) {
		imgLamp.frame.size.width *= 1.2
		imgLamp.frame.size.height *= 1.2
	}

형변환

	@IBAction func typeCast(_ sender: AnyObject) {
		if let tmpButton = sender as? UIButton {
			tmpButton.setTitle("확대2", for: .normal)
		}
	}

loadImage 함수 구현

	func loadImage(fileName : String, fileType : String) -> UIImage? {
		if let path = Bundle.main.path(forResource: fileName, ofType: fileType) {
			return UIImage(contentsOfFile : path)
		} else {
			return nil;
		}
	}

	@IBAction func OnRadio1Change(_ sender: UISwitch) {
		imgLamp.image = loadImage( fileName : sender.isOn ? "lamp_on.png" : "lamp_off.png", fileType : "png" )
	}

TextField Delegate

	public func textFieldShouldReturn(_ textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
	{
		loadPageWithUrlString(urlString: urlTextField.text ?? "")
		
		// 포커스 해지
		view.endEditing(true)
		
		return true;
	}

배열추가, String format, 이미지 변경

	var flowerArray = [String]()

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		
		for i in 1...6 {
			flowerArray.append( String(format : "%02d.png", i))
		}
	}

	@IBAction func onBtnNextClick(_ sender: UIButton) {
		if sender.currentTitle == "이전" {
			current_img_index -= 1
		} else {
			current_img_index += 1
		}
		
		if current_img_index >= flowerArray.count {
			current_img_index = 0
		}
		
		if current_img_index < 0 {
			current_img_index = flowerArray.count - 1
		}
		
		imgLamp.image = UIImage(named : flowerArray[current_img_index])
	}

Timer

		// 1초에 한번씩 호출
		Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {
			(timer) -> Void in
//			NSLog("%G", #function)
			
			let dateFormatter = DateFormatter()
			dateFormatter.dateFormat = "yyyy M d HH:mm:ss"
			
			
			self.lblCurrentTime.text = "현재시간 : " + dateFormatter.string(from : Date())
		})

UIAlertController

	override func viewDidAppear(_ animated: Bool) {
		/*
		let messageBox = UIAlertView(title : "알림", message : "메시지", delegate : nil, cancelButtonTitle : "OK")
		messageBox.show()
		*/

		let messageBox = UIAlertController(title: "알림", message: "메시지", preferredStyle: .alert)
		messageBox.addAction(UIAlertAction(title : "OK", style : .default, handler : {
			(action) -> Void in
			print("OK 선택")
			
		}))
		
		messageBox.addTextField(configurationHandler: {
			(textfield) in
			textfield.backgroundColor = UIColor.yellow
		})
		
		present(messageBox, animated : true, completion : nil)
	}

picker

import UIKit

class ViewController: UIViewController,  UIPickerViewDataSource, UIPickerViewDelegate {
	
	@IBOutlet weak var imagePickerView: UIPickerView!
	@IBOutlet weak var selectedItemLable: UILabel!
	@IBOutlet weak var selectedImageView: UIImageView!
	
	var mArray = [String]()

	override func viewDidLoad() {
		super.viewDidLoad()
		// Do any additional setup after loading the view, typically from a nib.
		
		
		imagePickerView.dataSource = self
		imagePickerView.delegate = self
		
		for i in 1...6 {
			mArray.append(String(format: "%02d", i))
		}
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
	
	
	// picker 열의 개수
	public func numberOfComponents(in pickerView: UIPickerView) -> Int {
		return 1
	}
	
	// picker 행의 개수
	public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
		
		return mArray.count;
	}
	
	/*
	func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
		
		return mArray[row]
	}*/
	
	// picker 행의 높이 설정
	public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat
	{
		return 100;
	}
	
	// picker 행을 이미지로 표시
	public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView
	{
		let imageView = UIImageView(frame:CGRect(x:0, y:0, width:100, height:100));
		imageView.image = UIImage(named : mArray[row])
		return imageView
	}
	
	// 선택이벤트
	public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
		selectedItemLable.text = "선택 = " + mArray[row]
		selectedImageView.image = UIImage(named : mArray[row])
	}
}

이미지 비동기 로딩

       if let urlString = movieArray[indexPath.row].thumbnailUrl,
            let url = URL(string : urlString)
        {
            do {
                /*
                // 동기방식
                let imageData = try Data(contentsOf: url)
                cell.thumbnailImageView.image = UIImage(data : imageData)
                */
            } catch {
                
            }
            
            // 비동기방식
            let task = URLSession.shared.dataTask(with: url) {
                (data, response, error) -> Void in
                
                if let imageData = data {
                    DispatchQueue.main.async {
                        cell.thumbnailImageView.image = UIImage(data : imageData)
                    }
                }
            }
                
            task.resume()
        }
저작자 표시
신고

Raspberry PI -무선랜카드 AP모드로 사용하기

OS/Raspberry Pi 2017.05.22 23:31 Posted by 파란크리스마스

Raspberry PI -무선랜카드 AP모드로 사용하기

출처 : Using your new Raspberry Pi 3 as a WiFi access point with hostapd
라즈베리파이 활용강좌 : 라즈베리파이를 무선공유기(AP)로 활용하기 |
SETTING UP A RASPBERRY PI AS AN ACCESS POINT IN A STANDALONE NETWORK

최신으로 업데이트

$ sudo apt-get update;sudo apt-get upgrade -y

AP 관련 패키지 설치

$ sudo apt-get install hostapd bridge-utils iw
$ sudo apt-get install dnsmasq

wlan0 고정 아이피 설정

$ sudo vi /etc/dhcpcd.conf

아래 내용 하단에 추가

denyinterfaces wlan0

Network 설정 파일 백업하고 수정

$ sudo cp /etc/network/interfaces /etc/network/interfaces.bak
$ sudo vi /etc/network/interfaces

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.0.1
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.0.255
#    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

wlan 다시 시작

$ sudo service dhcpcd restart
$ sudo ifdown wlan0
$ sudo ifup wlan0

DHCP 서버 설정

$ sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
$ sudo vi /etc/dnsmasq.conf

interface=wlan0      # Use interface wlan0
listen-address=192.168.0.1 # Explicitly specify the address to listen on
bind-interfaces      # Bind to the interface to make sure we aren't sending things elsewhere
server=8.8.8.8       # Forward DNS requests to Google DNS
domain-needed        # Don't forward short names
bogus-priv           # Never forward addresses in the non-routed address spaces.
dhcp-range=192.168.0.2,192.168.0.20,255.255.255.0,24h # Assign IP addresses between 192.168.0.2 and 192.168.0.20 with a 24 hour lease time

hostapd.conf 파일 생성

$ sudo vi /etc/hostapd/hostapd.conf

# This is the name of the WiFi interface we configured above
interface=wlan0

# Use the nl80211 driver with the brcmfmac driver
driver=nl80211

# This is the name of the network
ssid=Pi3-AP

# Use the 2.4GHz band
hw_mode=g

# Use channel 6
channel=6

# Enable 802.11n
ieee80211n=1

# Enable WMM
wmm_enabled=1

# Enable 40MHz channels with 20ns guard interval
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

# Accept all MAC addresses
macaddr_acl=0

# Use WPA authentication
auth_algs=1

# Require clients to know the network name
ignore_broadcast_ssid=0

# Use WPA2
wpa=2

# Use a pre-shared key
wpa_key_mgmt=WPA-PSK

# The network passphrase
wpa_passphrase=raspberry

# Use AES, instead of TKIP
rsn_pairwise=CCMP

default hostapd 파일 수정

$ sudo vi /etc/default/hostapd

DAEMON_CONF="/etc/hostapd/hostapd.conf"

서비스 다시 시작

$ sudo service hostapd start  
$ sudo service dnsmasq start
저작자 표시
신고


 

티스토리 툴바