2012년 2월 22일 수요일

[IOS] 맥어드레스 받아오는법


UDID란? 다들 알다시피 아이폰이나 아이팟 아이패드의 고유 시리얼 넘버이다.
사실 이 UDID 자체로 기기 판별을 한다는게 그렇게 권장할만한 일은 아니지만 어플을 개발하다 보면 써야할수 밖에 없는 상황이 있을수가 있다. (중복 체크 라던지에 사용하는데 절대적 신뢰를 하면 안된다.)

그런데 애플이 IOS5 부터 UDID 를 얻는 API 만료시킨단다. -_-;
줬다가 뺏는건 무슨 심보인지 모르겠지만 아무튼 우리는 그게 중요한게 아니라. UDID를 대체할 수단을 찾아야 한다.

인터넷을 하기 위해서 랜카드(유선이든 무선이든)가 컴퓨터에 있어야 한다는건 다 아는 사실일 것이다.
TCP/IP 의 특성상 그 랜카드에는 MAC 어드레스라는 랜카드의 고유 넘버가 있다. 아니 있어야만 한다.

이 MAC 어드레스는 스마트폰에도 예외는 아니다. 스마트폰은 작은 컴퓨터나 마찬가지이고 그안에 들어가 있는 무선랜카드에는 맥주소가 엄연히 존재한다.

아이팟/아이폰/아이패드 마찬가지이다.

UDID 를 대체하기에 전혀 손색이 없다. 혹자는 맥주소는 변조가 되지 않냐고 하지만 그건 해킹폰에서나 가능한 이야기고 어차피 해킹폰에서는 마음먹으면 UDID도 변조 가능하므로 언급할 가치는 없어 보인다. 앞에서도 말했듯이 절대적인 신뢰 고유값으로 사용하기엔 UDID 나 맥주소나 무리이긴 마찬가지이다. 하지만 일례를 들어 전자쿠폰 발행에서 한기기에서 여러번 받을수 없게 한다던지. 기기별 통계자료를 모은다던지에 있어서 위의 두 고유값은 유용한 값이된다. 이 값들을 마치 ID 처럼 사용하는 개발자는 당연히 없으리라 믿는다.

구글을 검색해보면 몇가지 소스가 나오는데. 제대로 작동하는 소스는 없다.
제대로 작동 안한다기 보다는 약간 수정해줘야 확실히 동작한다.

왜냐하면 아이폰에는 en0 디바이스 가 있고  en1 이란 디바이스가 있는데 en0 가 wi-fi 를 담당하는 무선랜카드의 디바이스명이고
en1 은 3G를 담당하는 모듈이다. 헌데 구글 소스는 현재 IP 주소를 받아온 즉, 활성화된 디바이스의 맥주소를 가져오려고 시도하게 되므로
3G가 켜져있는 상태에선 맥주소를 못가져 온다. (3G 디바이스엔 맥주소가 없는모양 )

아무튼 그래서 우리는 딱 집어서! en0 디바이스의 맥주소를 가져와! 라고 해줘야 한다. 
자그럼 아이폰에서 en0 의 mac 주소를 가져오는 소스를 공개하도록 하겠다.

--- MacAddress.h
char*  getMacAddress(char* macAddress, char* ifName); //간단히 함수만 정의 해주면 된다.

--- MacAddress.c
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <ifaddrs.h>

char*  getMacAddress(char* macAddress, char* ifName) {
    
    int  success;
    struct ifaddrs * addrs;
    struct ifaddrs * cursor;
    const struct sockaddr_dl * dlAddr;
    const unsigned char* base;
    int i;
    
    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != 0) {
            if ( (cursor->ifa_addr->sa_family == AF_LINK)
                && (((const struct sockaddr_dl *) cursor->ifa_addr)->sdl_type == 0x06) && strcmp(ifName,  cursor->ifa_name)==0 ) {
                dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
                base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
                strcpy(macAddress, ""); 
                for (i = 0; i < dlAddr->sdl_alen; i++) {
                    if (i != 0) {
                        strcat(macAddress, ":");
                    }
                    char partialAddr[3];
                    sprintf(partialAddr, "%02X", base[i]);
                    strcat(macAddress, partialAddr);
                    
                }
            }
            cursor = cursor->ifa_next;
        }
        
        freeifaddrs(addrs);
    }    
    return macAddress;
}


위의 두 파일을 프로젝트에 포함시키고.
사용하고자 하는 곳에서.

#import "MacAddress.h" //헤더파일 임포트~

char* macAddressString= (char*)malloc(18);
NSString *macAddress= [[NSString allocinitWithCString:getMacAddress(macAddressString,"en0")
                                                   encoding:NSMacOSRomanStringEncoding];
NSLog(macAddress);

이렇게 사용해주시면 되겠다.


2012년 2월 13일 월요일

[IOS] MPMoviePlayer PlaybackState


[MPMoviePlayerController alloc] 로 변수 선언

ex)
//------ 플레이어 생성할 함수 --------
MPMoviePlayerController *player =  [[MPMoviePlayerController alloc] initWithContentURL:url];
...
...
...

[[NSNotificationCenter defaultCenter] addObserver:self
                                 selector:@selector(moviePlayerPlaybackStateDidChange:)
                                 name:MPMoviePlayerPlaybackStateDidChangeNotification
                                  object:nil];
//------------------------------------

//---------- 호출될 함수 ------------
-(void) moviePlayerPlaybackStateDidChange:(NSNotification*)notification {
        NSLog(@"moviePlayerPlaybackStateDidChange");
        MPMoviePlayerController *moviePlayer = notification.object;
        MPMoviePlaybackState playbackState = moviePlayer.playbackState;
        switch (playbackState) {
                case MPMoviePlaybackStateStopped:
                        NSLog(@"MPMoviePlaybackStateStopped");
                        break;
                case MPMoviePlaybackStatePlaying:
                        NSLog(@"MPMoviePlaybackStatePlaying");
                        break;
                case MPMoviePlaybackStatePaused:
                        NSLog(@"MPMoviePlaybackStatePaused");
                        break;
                case MPMoviePlaybackStateInterrupted:
                        NSLog(@"MPMoviePlaybackStateInterrupted");
                        break;
                case MPMoviePlaybackStateSeekingForward:
                        NSLog(@"MPMoviePlaybackStateSeekingForward");
                        break;
                case MPMoviePlaybackStateSeekingBackward:
                        NSLog(@"MPMoviePlaybackStateSeekingBackward");
                        break;
                default:
                        break;
        }
}

[IOS] MPMoviePlayerController의 Notifications목록



MPMovieDurationAvailableNotification

동영상 객체의 총 재생시간을 알아낼 경우 알림이 발생한다. 총 재생시간은 MoviePlayerController.property에 반영된다.

MPMovieMediaTypesAvailableNotification
동영상 객체의 미디어 타입이 파악된 경우 알림이 발생한다. 지원되는 미디어 타입은 MoviePlayerController.movieMediaTypes에 반영된다.

MPMovieNaturalSizeAvailableNotification
동영상 객체의 프레임 사이즈가 처음 파악된 경우, 혹은 그 후에라도 변경된 경우 알림이 발생한다. 프레임 사이즈값은 MoviePlayerController.naturalSize에 반영된다
MPMoviePlayerContentPreloadDidFinishNotification
observer에게 동영상이 메모리에 올라가서 재생준비가 완료되었다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 만약 로드중에 오류가 발생한다면 알림 객체의 userinfo는 "error"키에 오류를 서술하는 NSError객체를 가지게 된다 (iOS 3.2 버전부터 Deprecated되었다. 플레이어가 준비되었는지 알고 싶을 경우 이 대신 MPMoviePlayerLoadStateDidChangeNotification notificaton을 사용하라
MPMoviePlayerDidEnterFullscreenNotification
observer에게 동영상 플레이어가 전체화면 모드로 재생이 된다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 사용자의 조작이 notification을 유발할 수 있다
MPMoviePlayerDidExitFullscreenNotification
observer에게 동영상 플레이어가 전체화면 모드에서 빠져나왔다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 사용자의 조작이 notification을 유발할 수 있다
MPMoviePlayerLoadStateDidChangeNotification
observer에게 네트워크 버퍼링 상태가 변했다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 현재 버퍼링 상태는 MoviePlayerController.loadState에서 확인할 수 있다
* MPMovieLoadState :
MPMovieLoadStateUnknown : 상태를 알 수 없다
MPMovieLoadStatePlayable : 충분한 버퍼가 모여서 재생할 수 있지만, 재생이 끝나기 전에 끊길 수 있다.
MPMovieLoadStatePlaythroughOK : 충분한 버퍼가 모여서 끊김없이 재생할 수 있다
MPMovieLoadStateStalled : 아직 충분한 버퍼가 모이지 않았기 떄문에 저장된 버퍼 이후에서는 일시정지 될 수 있다.
MPMoviePlayerNowPlayingMovieDidChangeNotification
observer에게 재생하는 동영상이 변경되었다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 현재 재생되는 동영상의 주소는 MoviePlayerController.contentURL에서 확인할 수 있다

MPMoviePlayerPlaybackDidFinishNotification
observer에게 동영상의 재생이 끝났다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. userInfo의MPMoviePlayerPlaybackDidFinishReasonUserInfoKey키에는 동영상이 종료된 이유를 나타낸다. 이 notification은 오류로 이노하여 재생이 실패했을때에도 발생한다. 이 notification은 동영상을 전체화면으로 재생하던 중 사용자가 Done버튼을 눌렀을때에는 발생하지 않는다. Done버튼이 눌렸을경우에는 동영상 재생이 일시정지 된 상태에서 전체화면에서 빠져나오기 때문이다. 이런경우에는 MPMoviePlayerDidExitFullscreenNotification등과 같은 notification을 확인해야 한다.
MPMoviePlayerPlaybackStateDidChangeNotification
observer에게 동영상 재생상태가 변경되었다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 동영상의 재생상태는 사용자의 행위 혹은 프로그램 로직상에의해 변경될 수 있다. 현재 재생되는 동영상의 상태는 MoviePlayer.playbackState에서 확인할 수 있다
* MPMoviePlaybackState : 
MPMoviePlaybackStateStopped : 동영상이 정지되어있으며, 동영상의 처음부터 재생될것이다
MPMoviePlaybackStatePlaying : 현재 동영상이 재생중이다
MPMoviePlaybackStatePaused : 동영상이 일시정지되었다. 일시정지 된 시점부터 다시 재생될 것이다.
MPMoviePlaybackStateInterrupted : 동영상 재생이 일시적으로 멈추었다. 대개 동영상 버퍼가 부족한 이유이다.
MPMoviePlaybackStateSeekingForward : 동영상 끝을향해 빨리감기중이다
MPMoviePlaybackStateSeekingBackward : 동영상의 처음을 향해 빨리감기중이다.
MPMoviePlayerScalingModeDidChangeNotification
observer에게 동영상 플레이어의 scaling mode(화면 크기)가 변경되었다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 사용자의 조작이 notification을 유발할 수있다.
MPMoviePlayerThumbnailImageRequestDidFinishNotification
observer에게 동영상 섬네일 제작이 완료되었다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 이 notification에는 MPMoviePlayerThumbnailImageKey와 MPMoviePlayerThumbnailTimeKey키가 있으며, 만약 오류가 발생한 경우 MPMoviePlayerThumbnailErrorKey와 MPMoviePlayerThumbnailTimeKey키를 갖는다.
MPMoviePlayerWillEnterFullscreenNotification
observer에게 동영상 플레이어가 전체화면으로 들어가려 한다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 이 notification에는 전체화면으로 들어가기 위한 화면 전환 애니메이션에 대한 키를 갖는데 이 키에 대해서는 Fullscreen Notification Keys 페이지에 기록되어있다. 사용자 조작이 notification을 유발할 수 있다.
MPMoviePlayerWillExitFullscreenNotification
observer에게 동영상 플레이어가 전체화면에서 나오려 한다는것을 알린다. 해당 동영상 플레이어는 notification의 인자로 전달된다. 이 notification에는 전체화면에서 나오기 위한 화면 전환 애니메이션에 대한 키를 갖는데 이 키에 대해서는 Fullscreen Notification Keys 페이지에 기록되어있다. 사용자 조작이 notification을 유발할 수 있다.
MPMovieSourceTypeAvailableNotification
이 notification은 동영상의 원본 타입에 대해 모르고 있다가 추후에 알게되었을 경우 발생된다. 원본 타입은 MoviePlayerController.movieSource에 반영된다
* movieSource : 이 속성의 기본 값은 MPMovieSourceTypeUnknown이다. 이 속성은 동영상 재생 시스템에게 동영상을 어떻게 다운로드하고 버퍼링 할것인가에 대해서 알려준다. 만약 동영상의 원본타입을 안다면, 이 값을 동영상 재생전에 설정해 주는것이 동영상 버퍼링 시간을 단축시켜 줄 수 있다. 만약 동영상 재생전에 이 값을 직접 설정하지 않는다면 MPMoviePlayerContoller는 정보를 직접 얻어야 하며, 이는 재생시간의 지연을 일으킬 수 있다

2012년 2월 10일 금요일

[IOS] ARC 해제 하는 방법

ARC는 무척 편한 방법이지만 많은 외부 라이브러리가 ARC에 맞지 않게 되어있다.
Xcode 4.2에서 특정 소스별로 ARC를 해제하는 방법은 아래와 같다.


1. Xcode project tree를 클릭
2. Target을 클릭
3. Build Phases tab을 선택
4. Compile Sources section을 확장
5. ARC에서 제외하고 싶은 하나 또는 더 많은 파일을 선택
6. 엔터키를 한 번친다.
7. -fno-objc-arc 를 타이핑
8. 엔티키를 다시 친다.
9. 각각 파일은 이제 -fno-objc-arc 컴파일러 옵션이 켜졌고 ARC에서 제외될 것이다.

2012년 2월 9일 목요일

[IOS] IOS 오픈소스


<네비게이션 바 아래에 동적으로 늘어나는 옵션 메뉴 넣기>
https://github.com/digdog/DDActionHeaderView

<OAuth>
http://code.google.com/p/oauthconsumner/
http://code.google.com/p/mpoauthconnection/

<페이스북, 트워터, 구글 리더 등에서 글, 그림, URL, 파일등을 공유하는 라이브러리>
http://getsharekit.com/

<네이트 Open API 라이브러리>
http://code.google.com/p/nate-ios-client-api/

<페이스북 연동 라이브러리>
https://github.com/facebook/facebook-ios-sdk

<TCP, UDP Socket Class 라이브러리>
http://code.google.com/p/cocoaasyncsocket/

<기본 클래스를 확장한 라이브러리>
https://github.com/enormego/cocoa-helpers

<iPhotoDiary, 육아일기 어플리케이션>
https://github.com/woohj70/iPhotoDiary

<DropBox를 통한 파일 공유 API 사용 예제 소스>
https://www.dropbox.com/developers/releases

<JSON Library> ----------------------------------------------------------------------------
JSONKit :
https://github.com/johnezang/JSONKit
SBJSON
https://github.com/stig/json-framework/
TouchJSON
https://github.com/TouchCode/TouchJSON
<XML Parser> ------------------------------------------------------------------------------
GDataXML :
http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/ (소스)
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml (해설)
TBXML : (read only, XPath 미지원)
http://www.tbxml.co.uk/TBXML/TBXML_Free.html
TouchXML : (read only, XPath 지원)
https://github.com/TouchCode/TouchXML
KissXML : (read/write)
http://code.google.com/p/kissxml/
여러가지 XML Parser에 대한 성능 비교 및 사용 용도 설명
http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project
<zip/unzip lib> ------------------------------------------------------------------------------
http://code.google.com/p/ziparchive/
<AVPlayer: LGPL로 FFmpeg, SoundTouch를 사용했다고 나오네요>
http://www.eplayworks.com/p/lgplinformation.html

<무인코딩 동영상 플레이어 VLC iPhone, iPad>
http://www.videolan.org/vlc/download-ios.html

<web server>
http://code.google.com/p/cocoahttpserver/

<bar code, QR code>
http://cafe.naver.com/mcbugi/79568 (http://zbar.sourceforge.net/)

<push notification service 관련 provider>
http://code.google.com/p/apns-php/ (PHP)
http://code.google.com/p/javapns/ (JAVA)
http://blog.toshsoft.de/index.php?/archives/3-Sending-Apple-Push-Notifications-APN-in-C-Updated-Using-CA-Cert.html (C)

<web 게시판과 연동>
http://code.google.com/p/cozymood/

http://cocoadev.tistory.com/#recentTrackback에서 공개한 내용임.

* 이미지 편집 함수 모음( 스케일, 회전, crop 등)
다양한 UI 구현
테이블뷰셀 커스터마이징
HTTP GET/POST 요청
XML 파싱
사진 앨범, 카메라, 지도 이미지 접근
맵뷰 및 위치정보
푸시 노티피케이션

<여러 UI 모음: photo viewer, etc>
http://github.com/facebook/three20 (초기에는 facebook 어플이었으나 현재는 여러 UI 모음으로 바뀜 )

|<map>
http://code.google.com/p/route-me/

<E-mail>
http://code.google.com/p/remail-iphone/
http://code.google.com/p/skpsmtpmessage/

<그래프>
http://code.google.com/p/core-plot/

<달력>
http://ved-dimensions.blogspot.com/2009/04/iphone-development-creating-native_09.html

<sqlite>
http://code.google.com/p/pldatabase/ (BSD license)
http://code.google.com/p/flycode/source/checkout (class rapper)

<계산기>
http://code.google.com/p/hpcalc-iphone/ (GPL V2 license)

<트위터 클라이언트>
http://github.com/blog/329-natsuliphone-iphone-twitter-client
http://code.google.com/p/tweetero/

<facebook>
http://github.com/facebook/facebook-iphone-sdk

<rss reader>
http://code.google.com/p/iphone-simple-rss-aggregator/

<ebook reader>
http://code.google.com/p/iphoneebooks/

<blog>
http://iphone.wordpress.org/

<백업, 동기화>
http://www.funambol.com/solutions/iphone.php
http://code.google.com/p/gris/ (구글 리더 동기화)

<time tracking>
http://github.com/freshbooks-addons/freshbooks-iphone-project

<게임>
http://code.google.com/p/cocos2d-iphone/
http://code.google.com/p/tris/ (테트리스)
http://code.google.com/p/mintgostop/ (고스톱)
http://www.joystiq.com/2009/03/24/carmack-releases-open-source-wolfenstein-for-iphone/
<google toolbox>
http://code.google.com/p/google-toolbox-for-mac/

<택배>
http://kldp.net/projects/taekbae/src

<이미지 프로세싱>
http://code.google.com/p/simple-iphone-image-processing/

<증강현실>
http://www.iphonear.org/

<coverflow 대체 구현>
http://apparentlogic.com/openflow/
http://www.chaosinmotion.com/flowcover.m (매가박스 어플에서 참고함)

<정규표현식 라이브러리>
http://blog.mro.name/2009/09/cocoa-wrapped-regexh/
http://regexkit.sourceforge.net/RegexKitLite/

<라이브러리 : JSON, DOM XML, Google Data APIs, Twitter, Flick, Game Engines, Unit Testr>
http://www.codingventures.com/2008/12/useful-open-source-libraries-for-iphone-development/


<기타>
http://open.iphonedev.com/
http://joehewitt.com/post/the-three20-project/


[출처] iPhone용 Open Source 모음  (맥부기 애플(iOS,Mac) 개발자모임) |작성자 낙수 => http://blog.naver.com/deepblue28/140144836843