2015/02/13

[iOS] OpenSSL을 iOS용으로 컴파일하기.

단계별로, 직접 컴파일 하는 방법과, build script를 이용해서 자동으로 하는 방법이 있습니다.

1. 자동으로 하는 방법

 웹사이트 :  https://github.com/x2on/OpenSSL-for-iPhone
 위 웹사이트에서 소스를 내려받습니다. (Download Zip)
 터미널에서 build-libssl.sh 를 실행하면, 자동을 만들어 줍니다.

 5개의 lib를 만들고, 그것을 하나로 합쳐서, universal lib로 만들어줍니다.
 해당 라이브러리는 /lib 밑에 libcrypto.a, libssl.a로 생성이 되고, /include에 헤더파일을 만들어 줍니다.
 사용하기 위해서는 lib에 있는 2개의 lib를 프로젝트에 추가하고, include를 프로젝트에서 찾을 수 있도록 추가해주면 됩니다.

2. 직접 컴파일하는 방법

- 소스 구하기.

  : 웹사이트(www.openssl.org)에서 버전을 내려 받습니다. 웹사이트에서 받거나 curl을 이용해서 받을 수 있습니다. 다운받을 버전은 1.0.1l 버전입니다.

DavidBaeui-iMac:Test DavidBae$ curl -O https://www.openssl.org/source/openssl-1.0.1l.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 4326k  100 4326k    0     0   279k      0  0:00:15  0:00:15 --:--:--  820k


- 받은 파일 압출 풀기.

  : Finder에서 풀거나, tar로 압축 풀기.

DavidBaeui-iMac:Test DavidBae$ mkdir src
openssl-1.0.1l.tar.gz src
DavidBaeui-iMac:Test DavidBae$ tar zxf openssl-1.0.1l.tar.gz -C /Users/DavidBae/Downloads/OpenSSL/Test/src
 이제 소스는 src 에 들어 있습니다.

- 소스에서 내용을 수정합니다.

//파일이름: crypto/ui/ui_openssl.c
//413 line
//static volatile sig_atomic_t intr_signal; //sig_atomic_t를 int로 변경
static volatile int intr_signal;
 : 소스의 413라인 쯤에서, sig_atomic_t 를 int로 변경해야 합니다.

소스가 준비가 되었으면, 총 5가지 타겟으로 컴파일을 하게 됩니다.
먼저, 시뮬레이터에서 사용할 32bit(i386), 64bit(x86_64)버전,
그리고, 실제 iOS에서 사용할 armv7, armv7s, arm64 버전을 각각 만듭니다.
아래에서 각각 만들고 마지막에 만들어진 5개를 하나의 lib로 묶는 작업을 합니다.


- i386 타겟으로 컴파일하기.

결과를 저장할 디렉토리는 현재 디렉토리의 bin/iPhoneSimulator8.1-i386.sdk 입니다.
물론 만들어놔야 겠지요.

./Configure 명령으로 Makefile을 만듭니다. iphoneos-cross 옵션과, 결과를 저장할 곳을 지정합니다.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$./Configure iphoneos-cross --openssldir=/Users/DavidBae/Downloads/OpenSSL/Test/bin/iPhoneSimulator8.1-i386.sdk
..
..
make[1]: Nothing to be done for `links'.
generating dummy tests (if needed)...
make[1]: Nothing to be done for `generate'.

Configured for iphoneos-cross.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ //<--make파일이 다 만들어졌습니다.

이제 make파일을 수정해야합니다.
makefile을 열어서 아래부분을 수정합니다.

CC = /Applications/Xcode.app/Contents/Developer/usr/bin/gcc -arch i386
//CFLAG= -DOPENSSL_THREADS.....
CFLAG= -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -miphoneos-version-min=7.0 -DOPENSSL....//원래 있던 옵션은 그대로 연결..

makefile내부의 CFLAG에 -isysroot 옵션을 추가해 줍니다. makefile을 저장합니다.
Make를 실행합니다.

DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make
.....
making all in tools...
make[1]: Nothing to be done for `all'.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make install
..
..
cp openssl.pc /Users/DavidBae/Downloads/OpenSSL/Test//bin/iPhoneSimulator8.1-i386.sdk/lib/pkgconfig
chmod 644 /Users/DavidBae/Downloads/OpenSSL/Test//bin/iPhoneSimulator8.1-i386.sdk/lib/pkgconfig/openssl.pc
DavidBaeui-iMac:openssl-1.0.1l DavidBae$
//완료되었음. bin/iPhoneSimulator8.1-i386.sdk 아래에 보면 있습니다.
결과는 /User/DavidBae/Download/OpenSSL/Test/bin/iPhoneSimulator8.1-i386.sdk 디렉토리에 들어 있습니다.
 여기에 있는 lib는 simulator의 32비트 환경에서만 동작하게 됩니다.
 다른 타겟으로도 컴파일하고, 이것과 같이 합쳐두어야 모든 플랫폼에서 사용할 수 있는 universal library가 됩니다.

- x86_64 타겟으로 컴파일하기.

결과를 저장할 디렉토리는 현재 디렉토리의 bin/iPhoneSimulator8.1-x86_64.sdk 입니다.
물론 만들어놔야 겠지요.

./Configure 명령으로 Makefile을 만듭니다. 옵션으로 darwin64-x86_64-cc가 사용되어 i386과는 다르게 설정합니다. 출력할 디렉토리도 같이 설정해 줍니다.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ ./Configure darwin64-x86_64-cc --openssldir=/Users/DavidBae/Downloads/OpenSSL/Test//bin/iPhoneSimulator8.1-x86_64.sdk
...
...
generating dummy tests (if needed)...
make[1]: Nothing to be done for `generate'.

Configured for darwin64-x86_64-cc.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$

makefile 변경하기.
CC = /Applications/Xcode.app/Contents/Developer/usr/bin/gcc -arch x86_64
//CFLAG= -DOPENSSL_THREADS.....
CFLAG= -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.1.sdk -miphoneos-version-min=7.0 -DOPENSSL....//원래 있던 옵션은 그대로 연결..

makefile내부의 CC를 변경하고, CFLAG에 -isysroot 옵션을 추가해 줍니다. makefile을 저장합니다.
Make를 실행합니다.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make
.....
making all in tools...
make[1]: Nothing to be done for `all'.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make install
..
..
cp openssl.pc /Users/DavidBae/Downloads/OpenSSL/Test//bin/iPhoneSimulator8.1-x86_64.sdk/lib/pkgconfig
chmod 644 /Users/DavidBae/Downloads/OpenSSL/Test//bin/iPhoneSimulator8.1-x86_64.sdk/lib/pkgconfig/openssl.pc
DavidBaeui-iMac:openssl-1.0.1l DavidBae$
//완료되었음. bin/iPhoneSimulator8.1-x86_64.sdk 아래에 보면 있습니다.


bin의 iPhoneSimulator8.1-x86_64.sdk의 lib와 include에 파일이 생성이 됨.

- armv7 타겟으로 컴파일하기.

결과를 저장할 디렉토리는 현재 디렉토리의 bin/iPhoneSimulator8.1-x86_64.sdk 입니다.
물론 만들어놔야 겠지요.

./Configure 명령으로 Makefile을 만듭니다. 옵션으로 darwin64-x86_64-cc가 사용되어 i386과는 다르게 설정합니다. 출력할 디렉토리도 같이 설정해 줍니다.

DavidBaeui-iMac:openssl-1.0.1l DavidBae$ ./Configure iphoneos-cross --openssldir=/Users/DavidBae/Downloads/OpenSSL/Test/bin/armv7/
...
...
generating dummy tests (if needed)...
make[1]: Nothing to be done for `generate'.

Configured for iphoneos-cross.

DavidBaeui-iMac:openssl-1.0.1l DavidBae$ 

makefile 변경하기.
CC = /Applications/Xcode.app/Contents/Developer/usr/bin/gcc -arch armv7
//CFLAG= -DOPENSSL_THREADS.....
CFLAG= -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -miphoneos-version-min=7.0 -DOPENSSL....//원래 있던 옵션은 그대로 연결.. CFLAG에 다른 -isysroot가 있는지 확인이 필요함.

makefile내부의 CC를 변경하고, CFLAG에 -isysroot 옵션을 추가해 줍니다. makefile을 저장합니다.
Make를 실행합니다.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make
.....
making all in tools...
make[1]: Nothing to be done for `all'.
DavidBaeui-iMac:openssl-1.0.1l DavidBae$ make install
..
..
cp openssl.pc /Users/DavidBae/Downloads/OpenSSL/Test//bin/armv7/lib/pkgconfig
chmod 644 /Users/DavidBae/Downloads/OpenSSL/Test//bin/armv7/lib/pkgconfig/openssl.pc
DavidBaeui-iMac:openssl-1.0.1l DavidBae$
//완료되었음. bin/armv7 아래에 보면 있습니다.

bin/armv7/lib와 include에 파일이 생성이 됨.

- armv7s 타겟으로 컴파일하기.
: armv7을 armv7s로 변경해서, 진행

- arm64 타겟으로 컴파일하기.
: arm7s를 arm64로 변경해서 진행


- Universal Library 만들기

 만들어진 5개의 lib를 하나로 합친다.

DavidBaeui-iMac:openssl-1.0.1l DavidBae$ lipo -create /Users/DavidBae/Downloads/OpenSSL/Test/bin/i386/lib/libssl.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/x86_64/lib/libssl.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/armv7/lib/libssl.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/armv7s/lib/libssl.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/arm64/lib/libssl.a -output /Users/DavidBae/Downloads/OpenSSL/Test/lib/libssl.

DavidBaeui-iMac:openssl-1.0.1l DavidBae$ lipo -create /Users/DavidBae/Downloads/OpenSSL/Test/bin/i386/lib/libcrypto.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/x86_64/lib/libcrypto.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/armv7/lib/libcrypto.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/armv7s/lib/libcrypto.a /Users/DavidBae/Downloads/OpenSSL/Test/bin/arm64/lib/libcrypto.a -output /Users/DavidBae/Downloads/OpenSSL/Test/lib/libcrypto.a

DavidBaeui-iMac:openssl-1.0.1l DavidBae$

OpenSSL에 대한 라이브러리가 생성이 되었다.

1번에서 build-libssl.sh 을 실행하면, 2번을 했던거와 같은 방법으로, 라이브러리를 만들어 준다.

잘 사용하시길....



2015/01/20

[iOS] CoreData에서 Entity의 개수를 효율적으로 읽어오기.

먼저 TableViewController의 경우, NSFetchedResultController를 사용하면 가장 효율적으로 관리할 수 있습니다.
특정 개수만 로딩 시켜서, 화면에 표시하므로 모든 데이터를 가져올 필요가 없게 됩니다.

하지만, 특정 경우, 지금 그 Entity의 개수가 몇개인지 알아야 할 경우가 있습니다.
이런때, 해당 Entity가 데이터가 크면, 그 개수 만큼의 NSManagedObject가 만들어지고, 데이터도 다 로딩 되므로, 순간 메모리 사용량이 커지게 됩니다.

이 경우, NSFetchRequest의  setIncludeSubentities를 NO로 해서 subentity들이 로딩 되지 않도록 하고,
context의 countForFetchRequest를 사용해서 해당되는 개수만 읽어 올 수 있게 됩니다.

참조: StackOverflow: Cocoa Core Data efficient way to count entities!

[iOS] unwind 함수를 코딩으로 호출하기.

Storyboard에서 Exit할 수 있는 Unwind segue를 만든다.
- 버튼에서 Exit로 Ctrl-Drag에서 만들 수도 있고
- 해당 View Controller의 아이콘에서 Exit로 Ctrl-Drag해서 Unwind segue를 만든다.

왼쪽 리스트에서 Unwind Segue from XXViewController를 선택하고, 오른쪽 Attribute Inspector에서 Identifier를 설정할 수 있다.

그러면,  코드상에서 performSegueWithIdentifier로 호출할 수 있다.

[참고: stackoverflow - How to perform Unwind segue programmatically?]


2014/12/26

[iOS] 원형의 그라디언트 이미지를 그려봅시다. (Rendering a radial gradient)

Radial Gradient

원형으로 배경을 은은하게 채워야하는 경우에, 아래와 같이 그림이 필요합니다.
이미지를 만들어서 넣으면 좋겠지만, Core Graphics를 사용해서 그릴 수 있습니다.
만들 이미지
source code
- (void)drawRadialGradient:(UIColor *)startColor
                  endColor:(UIColor *)endColor
                startPoint:(CGPoint)startPoint
               startRadius:(CGFloat)startRadius
                  endPoint:(CGPoint)endPoint
                 endRadius:(CGFloat)endRadius
                   context:(CGContextRef)context
{
    CGColorRef colorRef = startColor.CGColor;
    CGColorRef endColorRef = endColor.CGColor;
    NSArray *marrColors=[NSArray arrayWithObjects:
                         (__bridge id)colorRef,    //start color
                         (__bridge id)endColorRef, //end color
                         nil];
    CFArrayRef colors =(__bridge CFArrayRef)(marrColors);
    CGColorSpaceRef colorSpc = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpc, colors, Nil);
    
    // generates Radial Gradient
    CGContextDrawRadialGradient(context, gradient,
                                startPoint, startRadius,
                                endPoint, endRadius,
                                0);
    CGColorSpaceRelease(colorSpc);
    CGGradientRelease(gradient);
}
 



이 함수를 이용해서, 중심에 그리면, 위 만들이미지와 같은 효과를 얻을 수 있습니다.

Drawing a radial gradient like Lens


그러면, Gradient에 이미지를 추가하면 중간에 이미지가 추가가 됩니다.
source code
- (void)drawRadialGradient:(UIColor *)startColor
                  midColor:(UIColor *)midColor
                  endColor:(UIColor *)endColor
                startPoint:(CGPoint)startPoint
               startRadius:(CGFloat)startRadius
                  endPoint:(CGPoint)endPoint
                 endRadius:(CGFloat)endRadius
                   context:(CGContextRef)context
{
    CGColorRef colorRef = startColor.CGColor;
    CGColorRef midColorRef = midColor.CGColor;
    CGColorRef endColorRef = endColor.CGColor;
    NSArray *marrColors=[NSArray arrayWithObjects:(__bridge id)colorRef,
                         (__bridge id)midColorRef,
                         (__bridge id)endColorRef, nil];
    CFArrayRef colors =(__bridge CFArrayRef)(marrColors);
    CGColorSpaceRef colorSpc = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpc, colors, Nil);
    
    // generates Radial Gradient
    CGContextDrawRadialGradient(context, gradient,
                                startPoint, startRadius,
                                endPoint, endRadius,
                                0);
    CGColorSpaceRelease(colorSpc);
    CGGradientRelease(gradient);
}
호출하는 소스
- (void)drawRect:(CGRect)rect {
    
    CGContextRef context = UIGraphicsGetCurrentContext();

    
    // Drawing code
    UIColor *whiteColor = [UIColor whiteColor];
    UIColor *blueColor = [UIColor blueColor];
    UIColor *greenColor = [UIColor greenColor];
    
    CGSize size = self.frame.size;
    CGPoint center = CGPointMake(size.width/2, size.height/2);
    /*/
    [self drawRadialGradient:greenColor endColor:self.backgroundColor
                  startPoint:center startRadius:0
                    endPoint:center endRadius:size.width/2
                     context:context];
    /*/
    [self drawRadialGradient:greenColor midColor:blueColor endColor:whiteColor
                  startPoint:center startRadius:0
                    endPoint:center endRadius:size.width/2
                     context:context];
    CGPoint point2 = CGPointMake(size.width/2-15, size.height/2-15);
    [self drawRadialGradient:whiteColor endColor:greenColor
                  startPoint:point2 startRadius:0
                    endPoint:point2 endRadius:5
                     context:context];
    point2 = CGPointMake(size.width/2+15, size.height/2+15);
    [self drawRadialGradient:whiteColor endColor:greenColor
                  startPoint:point2 startRadius:0
                    endPoint:point2 endRadius:2
                     context:context];
     //*/
}


결과물
3가지 색으로만
3가지 색에, 점 2개 찍은것


나름 랜즈와 비슷한 것이 나온것 같군요.






2014/12/11

[iOS] NSString으로 된 값을 파일로 직접 저장하자.

현재 App의 디렉토리 Path를 읽어 오고, 거기에 파일 이름을 추가합니다.


 source code
- (NSURL *)urlForFilename:(NSString *)filename {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *urls = [fm URLsForDirectory:NSDocumentDirectory
                               inDomains:NSUserDomainMask];
    NSURL *directoryURL = urls[0];
    NSURL *fileURL = [directoryURL URLByAppendingPathComponent:filename];
    return fileURL;
}

이름을 정하고 나면, NSString에서 바로 저장합니다.


    BOOL status = [string writeToFile:[pathUrl.path stringByAppendingPathExtension:@"txt"]
                           atomically:YES 
                             encoding:NSUTF8StringEncoding 
                                error:&error];
        
    if (error != nil) {
        NSLog(@"save error: %@", [error description]);
    }
    if (status == NO) {
        NSLog(@"save error");
    }


파일로부터 데이터를 읽어 올 경우도, NSString의 카테고리를 이용합니다.

    NSString *string = [NSString stringWithContentsOfURL:pathUrl 
                                                encoding:NSUTF8StringEncoding 
                                                   error:&error];
    if (error != nil || string == nil) {
       NSLog(@"Can't load file: %@, error:%@", pathUrl.path, [error description]);
    }


만약, 문자열이 아닌 Binary데이터를 저장하려면, NSString대신, NSData의 카테고리 함수를 이용하면, 똑같이 사용이 가능합니다.

2014/10/10

[iOS] User Defined Runtime Attributes

User Defined Runtime Attributes란? 

Xcode의 Interface Builder에서 특정한 UI 객체에 사용자가 정의하는 값을 바로 입력하는 기능을 말합니다.
Storyboard에 정의된 객체에서 값을 설정할 수 있는 것으로, Identity Inspector tab에서 설정할 수 있습니다. 

InterfaceBuilder의 User Defined Runtime Attributes 설정 화면과 시뮬레이터 표시 내용.

위의 그림처럼 Interface Builder에서 UIView를 넣고, Identity Inspector Tab에서 값을 입력하게 되면, m파일에서 UIView의 객체를 연결해서, 직접 입력한 것처럼 동작하게 됩니다.

입력 할 수 있는 값은 어떤 것이 있을까요?

Boolean - BOOL
Number - NSNumber *
String - NSString *
Point - CGPoint
Size - CGSize
Rect - CGRect
Range - NSRange
Color - UIColor *
LocalizedString - NSString *
(Localizable.string 파일에서 Key를 입력하고, 해당 locale에 맞는 string을 입력)
Image - UIImage*




Xcode 6에서는 총 10가지를 입력할 수 있습니다.

위에 첫번째 이미지에서 layer.borderColor는 바로 설정할 수가 없습니다.
전달되는 객채는 UIColor이고, layer.borderColor는 CGColorRef를 사용하기 때문입니다.
가능한 방법은
CALayer의 카테고리를 생성하고, 그 카테고리에 setBorderColorFromUIColor 함수를 만들어 줍니다.
source code
#import "CALayer+extension.h"

@implementation CALayer (extension)
- (void)setBorderColorFromUIColor:(UIColor *)color
{
    self.borderColor = color.CGColor;
}
@end

h파일에도 함수를 선언해 주어야 합니다.
이제, InterfaceBuilder에서 layer.borderColorFromUIColor 를 사용해서, 색상을 설정할 수 있습니다.


위의 시뮬레이터에서 테두리 색상이 설정된 것을 볼 수 있습니다.


[참고]

- iOS-Blog : User Defined Runtime Attributes
- ATOMIC SPIN : Expanding User-Defined Runtime Attributes in Xcode with Objective-C




2014/09/12

[iOS] 물방울 모양의 UIView를 만들자.

UIView의 모양을 물방울 모양으로 변형을 해보겠습니다.

1. UIBezierPath를 이용해서, 물방울 모양의 Path를 만듭니다.

source code
- (UIBezierPath *)waterDropPath:(CGRect)frame
{
    //NSLog(@"makeWaterDropPathIn: %@", NSStringFromCGRect(frame) );
    float x = frame.origin.x;
    float y = frame.origin.y;
    float hW = frame.size.width/2.0f;
    float H = frame.size.height;
    
    CGPoint sp = CGPointMake(x+hW, y);      //Start point
    CGPoint cp = CGPointMake(x+hW, y+H-hW); //Center point
    
    CGPoint b1 = CGPointMake(x, y+H-hW);    //WaterDrop left point
    CGPoint c1 = CGPointMake(x+hW, y+hW+hW/2); //왼쪽 내려오는 부분에서 사용
    CGPoint c2 = CGPointMake(x, y+H-hW-hW);    
    CGPoint c3 = CGPointMake(x+hW+hW, y+H-hW-hW); //오른쪽 올라가는 부분에서 사용
    
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path setLineWidth:0.5f];
    
    [path moveToPoint:sp]; //시작점으로 이동
    
    [path addCurveToPoint:b1
             controlPoint1:c1
             controlPoint2:c2]; //왼쪽 물방울 내려오는 부분
    
    [path addArcWithCenter:cp
                     radius:hW//-0.5f
                 startAngle:DEGREE_TO_RADIAN(180)
                   endAngle:DEGREE_TO_RADIAN(0)
                  clockwise:NO]; //물방울 아래부분

    [path addCurveToPoint:sp
             controlPoint1:c3 
             controlPoint2:c1]; //오른쪽 올라가는 부분
    
    return path;
}

2. Path로 부터 현재 뷰의 layer의 mask를 설정합니다.

source code
- (void) setWaterDropClippingArea:(CGRect)frame
{
    //클립핑 영역을 만든다.
    [self setClippingAreaFromPath:[self waterDropPath:frame]];
}
- (void)setClippingAreaFromPath:(UIBezierPath *)path
{
    CAShapeLayer *mask = [CAShapeLayer layer];
    mask.path = path.CGPath;
    
    self.layer.mask = mask;
}

3. 결과물

 

 위 소스의 sp, cp, b1, c1, c2, c3 위치를 왼쪽에 표시하였습니다.