728x90

swift 기본문법

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

import UIKit

// var str:String ="Hello, playground"
var str = "Hello, playground"
str = "Hello, "

//
let myName = "bluexmas"

// char 타입
let lastName:Character = "류"

// int 타입
let age = 38

// boolean 타입
let isAult = true

print(isAult ? "성인" : "어린이")

// 범위연산자
for i in 1...5 {
    print(i)
}

// 자료형
print(Int.max)
print(Int8.max)
print(Int16.max)
print(UInt.max)

let num:Int8 = 10

let pi = 3.14159

// 자동 형변환 없음
//print(myName + age)
print(myName + String(age))

print("\(myName) 나이는 \(age)")

// 숫자형도 형변환이 없으면 더할수 없음
print(Double(num) + pi)

// 조건문
if str == "한글" {
    print("참")
} else if str == "play" {
    print("play도 아니다.")
} else {
    print("거짓")
}

if str != "최현택" && age == 38 {
    print("최현택은 아니지만 나이는 같다.")
}

// in line 
isAult ? print("성인") : print("청소년")


// switch
switch age {
case 0..<20:
    print("청소년")
case 20..<30:
    break // switch 를 빠져나감
case 30..<40:
    print("30대")
    fallthrough // break 와 다르게 이하  case 조건 실행
default:
    print("성인")
}

// 문자열 switch
switch lastName {
case "김", "이", "박":
    print("김이박")
default:
    print("test")
}

// 배열
let nameArray:[String] = ["추신수", "박찬호"]

var i = 1
var sum = 0
while i<=10 {
    sum += i
    i += 1
    print(sum)
}

구구단 출력

// 구구단
for i in 2...9 {
    print("\n \(i) 단\n")
    for j in 1...9 {
        print("\(i) * \(j) = \(i*j)")
    }
}

배열

// 배열
var arrray2:Array<string> = ["java", "c#", "delphi"]
var nameArray:[String] = ["java", "c#", "delphi"]

// 추가
nameArray.append("javascript")

// 삽입
nameArray.insert("sql", at: 2)

// 제거
nameArray.remove(at: 1)

print(nameArray)

// 대치
nameArray[0] = "자바"

// 출력
for i in 0...2 {
    print(nameArray[i])
}

// 배열의 Count
print("배열의 Count = \(nameArray.count)")

// 일부만 출력
print(nameArray[0...1])

// 전부 삭제
nameArray.removeAll()

Dictionary

// Dictionary
var capitalDic2:Dictionary<string, string=""> = ["한국" : "서울", "영국" : "런던", "미국" : "워싱턴"]
var capitalDic = ["한국" : "서울", "영국" : "런던", "미국" : "워싱턴"]
print(capitalDic["한국"])    // Optional("서울")

for capital in capitalDic.values {
    print(capital)
}

for (country, capital) in capitalDic {
    print("\(country)  국가의 수도는 \(capital)")
}

// 추가
capitalDic["중국"] = "배이징"
print(capitalDic)

// 삭제1
capitalDic.removeValue(forKey: "미국")
print(capitalDic)

// 삭제2
capitalDic["중국"] = nil
print(capitalDic)

// 전부삭제
capitalDic.removeAll()
print(capitalDic)

함수

// 함수
func printStr() {
    print(str)
}

func sum(lns : Int, rhs : Int) -> Int {
    return lns + rhs
}

print( sum(lns: 5, rhs: 3) )

튜플(Tuple)

// 튜플(Tuple)
func getMyInfo() -> (String, Int, String, String) {
    return ("블루", 10, "010-xxx-xxxx", "bluexmas@tistory.com")
}

let (name, age, phone, email) = getMyInfo()
print(name)
print(age)
print(phone)
print(email)

구조체

클래스와 다르게 구조체는 기본 자료형(int, boolean)처럼 대입시 별도의 메모리가 할당 되고, 클래스처럼 상속을 받을 수 없습니다.

// 구조체
struct UserInfo {
    var name : String
    var age : Int
    var email : String
    
    // swift 제고 초기화 함수
    init(name : String, age : Int, email : String) {
        self.name = name
        self.age = age
        self.email = email
    }
    
    func showInfo() {
        print("이름 : \(name), 나이 : \(age) 메일주소 : \(email)")
    }
}

var userInfo1 = UserInfo(name : "블루", age : 10, email : "bluexmas@tistyory.com")
var userInfo2 = UserInfo(name : "레드", age : 10, email : "bluexmas@tistyory.com")
userInfo1.showInfo()

var userArray:[UserInfo] = []
userArray.append(userInfo1)
userArray.append(userInfo2)

for info in userArray {
    info.showInfo()
}
728x90
728x90

Swift 3.1

출처 : mozilla-mobile/firefox-ios
아이폰 Swift 개발 #6 Web Browser App - Machine Learning and ...
[iOS] WebKit API 알아보기. : 네이버 블로그

세로모드 고정

출처 : Swift 3 how to lock orientation - Stack Overflow

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

 override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

override func viewDidLoad() {
    super.viewDidLoad()
}

URL 주소의 이미지 가져오기

출처 : swift3 - Swift 3: Display Image from URL - Stack Overflow

                let url = URL(string: hostUrl + (share_url as! String))
                NSLog("url = \(url?.absoluteString)")

                var data = NSData(contentsOf: url as! URL)
                var image = UIImage(data : data as! Data)

문자열 내장 합수

출처 : How does String.Index work in Swift 3
Index of a substring in a string with Swift

JavaScript(Alert,Confirm,Prompt)

출처 : WKWebViewでJavaScript(Alert,Confirm,Prompt)の処理
WKWebView 사용 시 필수적으로 넣어줘야 하는Delegate 넷.

오류 해결 / This application is modifying the autolayout engine from a background thread, which can lead to engine corruption

출처 : This application is modifying the autolayout engine from a background thread, which can lead to engine corruption - Stack Overflow

    func alert(message : String) {
        let alertView = UIAlertController(title: "파란크리스마스", message: message, preferredStyle: .alert)
        alertView.addAction(UIAlertAction(title: "확인", style: .default, handler: { (alertAction) -> Void in
            //logUserIn()
        }))
        //alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
        DispatchQueue.main.async {
            self.present(alertView, animated: true, completion: nil)
        }
    }

배포

출처 : 내가 만든 iOS앱을 앱스토어에 배포해보자 - xCode로 소스 업로드하기 ...

728x90
728x90

출처
Apple LLVM compilerと無名カテゴリ
Building static C++ lib for use with Objective-c app in Xcode 4
static library 빌드 및 라이브러리 사용 어플리케이션 통합 디버깅하기 - 아이폰 4.x
Using C/C++ static libraries from iPhone ObjectiveC Apps
Xcode architectureエラー
objective c에서 STL 사용하기
아이폰에서 C로 된 정적 라이브러리 사용하기
Xcode 4.0 에서 c로 된 static library link error 조치

testlib.h 파일

/*
 * testlib.h
 *
 *  Created on: 2012. 9. 6.
 *      Author: bluexmas
 */

#ifndef LIBTEST_H_
#define LIBTEST_H_

#if defined(_WIN32) || defined(__WIN32__)
	#define DLL_CALLCONV __stdcall
	#ifdef LIBTEST_EXPORTS
		#define DLL_API __declspec(dllexport)
	#else
		#define DLL_API __declspec(dllimport)
	#endif // LIBTEST_EXPORTS
#else 
	// try the gcc visibility support (see http://gcc.gnu.org/wiki/Visibility)
	#if defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
		#ifndef GCC_HASCLASSVISIBILITY
			#define GCC_HASCLASSVISIBILITY
		#endif
	#endif // __GNUC__
	#define DLL_CALLCONV
	#if defined(GCC_HASCLASSVISIBILITY)
		#define DLL_API __attribute__ ((visibility("default")))
	#else
		#define DLL_API
	#endif		
#endif // WIN32 / !WIN32

DLL_API const char *DLL_CALLCONV get_version(void);

#endif /* LIBTEST_H_ */

testlib.cpp 파일

/*
 * testlib.cpp
 *
 *  Created on: 2012. 9. 6.
 *      Author: bluexmas
 */

#include "testlib.h"

const char* get_version() {
  return "testlib ver 0.2";
}

makefile.iphone-debug 파일

RM := rm -rf

GCC_VERSION = 4.2
IPHONEOS_DEPLOYMENT_TARGET = 5.1
MACOSX_DEPLOYMENT_TARGET = 10.8

PLATFORM_SIM = iPhoneSimulator
PLATFORM_PHONE = iPhoneOS

ARCH_SIM = i386
ARCH_PHONE = armv7

TOOLCHAIN=/Volumes/Mac/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
DEVROOT=/Volumes/Mac/Applications/Xcode.app/Contents/Developer
PLATFORM_SIM_DEVELOPER_BIN_DIR = $(DEVROOT)/Platforms/$(PLATFORM_SIM).platform/Developer/usr/bin
PLATFORM_PHONE_DEVELOPER_BIN_DIR = $(DEVROOT)/Platforms/$(PLATFORM_PHONE).platform/Developer/usr/bin

SDKROOT_SIM = $(DEVROOT)/Platforms/$(PLATFORM_SIM).platform/Developer/SDKs/$(PLATFORM_SIM)$(IPHONEOS_DEPLOYMENT_TARGET).sdk
SDKROOT_PHONE = $(DEVROOT)/Platforms/$(PLATFORM_PHONE).platform/Developer/SDKs/$(PLATFORM_PHONE)$(IPHONEOS_DEPLOYMENT_TARGET).sdk

IDIR=./inc
CLANG=$(TOOLCHAIN)/clang
CLANGFLAGS_SIM=-x objective-c-header -O0 -g3 -Wall -c -fmessage-length=0 -DDEBUG=1
CLANGFLAGS=-x objective-c -O0 -g3 -Wall -c -fmessage-length=0
LIBTOOL=$(TOOLCHAIN)/libtool

SDIR=./src
ODIR=./lib

#CPP_SRCS = \
#	./src/testlib.cpp 

OBJS += \
	./lib/testlib.o-sim
	
CPP_DEPS += \
	./lib/testlib.d	-sim
	
USER_OBJS :=

LIBS :=	

# Each subdirectory must supply rules for building sources it contributes
$(ODIR)/%.o-sim: $(SDIR)/%.cpp
	@echo 'Building file: $<'
	@echo 'Invoking: Cygwin C++ Compiler'
	$(CLANG) -c $(CLANGFLAGS_SIM) -arch $(ARCH_SIM) -isysroot $(SDKROOT_SIM) -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o-sim=%.d-sim)" -I$(IDIR) -o "$@" "$<"
	@echo 'Finished building: $<'
	@echo ' '

# All Target
all: libtestlib-sim.a

# Tool invocations
libtestlib-sim.a: $(OBJS) $(USER_OBJS)
	@echo 'Building target: $@'
	@echo 'Invoking: GCC Archiver'
	$(LIBTOOL) -static -arch_only $(ARCH_SIM) -syslibroot $(SDKROOT_SIM) -o libtestlib-sim.a $(OBJS) $(USER_OBJS) $(LIBS)
	@echo 'Finished building target: $@'
	@echo ' '	
	
# Other Targets
clean:
	-$(RM) $(C++_DEPS)$(OBJS)$(C_DEPS)$(CC_DEPS)$(ARCHIVES)$(CPP_DEPS)$(CXX_DEPS)$(C_UPPER_DEPS) libtestlib-sim.a
	-@echo ' '

makefile.cygwin 파일(참고용)

RM := rm -rf

IDIR=./inc
CC=g++
CFLAGS=-I$(IDIR)

SDIR=./src
ODIR=./lib

#CPP_SRCS = \
#	./src/testlib.cpp 

OBJS += \
	./lib/testlib.o 
	
CPP_DEPS += \
	./lib/testlib.d	
	
USER_OBJS :=

LIBS :=	

# Each subdirectory must supply rules for building sources it contributes
$(ODIR)/%.o: $(SDIR)/%.cpp
	@echo 'Building file: $<'
	@echo 'Invoking: Cygwin C++ Compiler'
	$(CC) $(CFLAGS) -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o "$@" "$<"
	@echo 'Finished building: $<'
	@echo ' '

# All Target
all: libtestlib.a

# Tool invocations
libtestlib.a: $(OBJS) $(USER_OBJS)
	@echo 'Building target: $@'
	@echo 'Invoking: GCC Archiver'
	ar -r  "libtestlib.a" $(OBJS) $(USER_OBJS) $(LIBS)
	@echo 'Finished building target: $@'
	@echo ' '	
	
# Other Targets
clean:
	-$(RM) $(C++_DEPS)$(OBJS)$(C_DEPS)$(CC_DEPS)$(ARCHIVES)$(CPP_DEPS)$(CXX_DEPS)$(C_UPPER_DEPS) libtestlib.a
	-@echo ' '	

정적라이브러리 만들기

 

빌드옵션

Header Search Paths 추가

Build Phase -> Link Binary With Libraries 추가

정적 라이브러리 메소드 호출

#include "testlib.h" 추가

실행

버튼 선택

 

 

 

- end -

728x90
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90
728x90

ffmpeg 라이브러리를 이용해서 wowza서버를 사용하는 rtsp 플레이어를 제작해보았습니다.
소스는 iFrameExtractor 프로젝트에서 파일 오픈하는 부분을 rtsp 주소를 사용했고,
ffmpeg 라이브러리 경로를 따로 설정해서 컴파일 했습니다.

설치한 ffmpeg 라이브러리가 ios용으로 컴파일 되어 있어서
시뮬레이터에서는 테스트 할 수가 없네요.

iFrameExtractor 프로젝트는 ffmpeg 라이브러리만 사용했기 때문에 플레이는 되지만,
속도는 나오지 않습니다. OpenGL ES / SDL 라이브러리 이용해야 될 것 같네요.

출처

How can you pass YUV frames from FFmpeg to OpenGL ES?
TECH TUTORIAL ? HOW TO SETUP A SDL-READY XCODE4 PROJECT
CODEC_TYPE_VIDEO undefined
ffmpeg을 이용한 iOS 동영상 플레이어
<video> 태그를 이용하여 rstp 프로토콜의 스트리밍을 재생하고자 하고싶은데요...
Audio and Video HTML
myoutube or RTSP streaming support on chrome

소스 다운로드

jayrparro / iFrameExtractor

ffmpeg 라이브러리 경로 설정

오류 수정

CODEC_TYPE_VIDEO undefined 발생 한다면,
AVMEDIA_TYPE_VIDEO 로 수정

rtsp 주소 설정
iFrameExtractorAppDelegate.m

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
	//self.video = [[VideoFrameExtractor alloc] initWithVideo:[Utilities bundlePath:@"sophie.mov"]];
    //self.video = [[VideoFrameExtractor alloc] initWithVideo:[Utilities bundlePath:@"oh.mp4"]];
    self.video = [[VideoFrameExtractor alloc] initWithVideo:@"rtsp://192.168.0.13/vod/mp4:sample.mp4"];
	[video release];

	// set output image size
	video.outputWidth = 426;
	video.outputHeight = 320;
	
	// print some info about the video
	NSLog(@"video duration: %f",video.duration);
	NSLog(@"video size: %d x %d", video.sourceWidth, video.sourceHeight);
	
	// video images are landscape, so rotate image view 90 degrees
	[imageView setTransform:CGAffineTransformMakeRotation(M_PI/2)];
    [window makeKeyAndVisible];
}

YUV 데이터 -> RGB 데이터 소스
VideoFrameExtractor.m

-(void)convertFrameToRGB {	
	sws_scale (img_convert_ctx, pFrame->data, pFrame->linesize,
			   0, pCodecCtx->height,
			   picture.data, picture.linesize);	
}

실행


728x90
728x90

출처

iOS용 FFmpeg 빌드
[iPhone] ffmpeg 빌드하기
How to cross compile ffmpeg for iOS (iPhone and iPad)
Build m4, autoconf, automake, libtool on Mac OS X Lion
http://www.slideshare.net/hypermin/html5-video

make 커맨드 설치

pkg-config 설치

pkg-config 다운로드

gas-preprocessor 다운로드

gas-preprocessor 다운로드

build-essentials 스크립트 다운로드및 실행

설치되는 항목 m4, autoconf, automake, libtool

https://gist.github.com/1397146

- 디렉토리구조

$HOME
├ local
└ Builds
   └ build-essential
      ├ build-essential.sh
      └ src

- 실행

$ chmod 755 build-essential.sh
$ ./build-essential.sh

- 경로 추가 (~/.profile)

PATH=$PATH:/Users/자신의계정/local/bin

- 확인

압축풀기

- 다운로드

ffmpeg 다운로드

- 압축풀기

$ tar xvfz ffmpeg-0.8.11.tar.bz2

config.sh 파일

./configure --enable-cross-compile \
  --arch=arm \
  --target-os=darwin \
  --cc='/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-llvm-gcc-4.2' \
  --as='./gas-preprocessor/gas-preprocessor.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-llvm-gcc-4.2' \
  --cpu=cortex-a8 \
  --enable-pic \
  --disable-yasm \
  --sysroot='/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk' \
  --extra-cflags='-mfpu=neon -pipe -Os -gdwarf-2 -miphoneos-version-min=5.0' \
  --extra-ldflags='-arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk -miphoneos-version-min=5.0' \
  --disable-asm \
  --disable-doc \
  --disable-ffmpeg \
  --disable-ffplay \
  --disable-ffprobe \
  --disable-ffserver \
  --enable-avdevice \
  --disable-devices \
  --disable-filters \
  --disable-yasm \
  --enable-network \
  --enable-protocol=tcp \
  --enable-demuxer=rtsp \
  --enable-decoder=h264

$ ./config.sh

$ make

$ sudo make install

728x90

+ Recent posts