2012/12/13 15:10

iPhone5의 스크린 크기와 iPhone4, iPhone5 호환하여 코딩하기 -- iOS (iPhone)



iPhone4에서 컨트롤을 전체로 지정하기 위해 320 * 480으로 지정한다.

[mWebView setFrame:CGRectMake(0, 0, 320, 480)];

그런데, 이런 코딩은 iPhone5에서는 아래가 잘려서 나오게 된다.
이유는 iPhone5가 320 * 568의 해상도를 가지고 있기 때문이다.

그래서 필자는 컨트롤의 크기를 지정하는 코딩을 특히 전체로 보여져야 하는 부분의 코딩을 아래와 같이 수정하였다.


#define PHONE_SCREEN_HEIGHT   CGRectGetHeight([UIScreen mainScreen].applicationFrame)
#define PHONE_SCREEN_WIDTH    CGRectGetWidth([UIScreen mainScreen].applicationFrame)

[mWebView setFrame:CGRectMake(0, 0, PHONE_SCREEN_WIDTH, PHONE_SCREEN_HEIGHT)];


추가) 2012.12.20

iPhone5에서 TableView의 하단 (yPosition 480을 넘기는 Cell)이 안눌리는 현상이 있었는데 아래와 같이 해결하였다.
원인은 View의 크기 등을 위의 방법으로 늘려도 전체의 bounds가 늘어나지 않으면 응답을 못받는 것이었으며, 아래의 해결책들이 바로 이 문제를 다룬 것이다.


방법1) xib파일의 Attributes Inspector에서 Window section 중 Full Screen At Launch를 체크

방법2) xib파일에서 필자처럼 Window section이 없는 경우, Attributes Inspector에서 Simulated Metrics section 중 Size를 Retina 4 Full Screen으로 변경할 것.

보통 iPhone4에서 개발 시 위의 Size를 None이나 Freeform으로 지정했는데 이것이 문제였다.
iPhone5는 물론 아래 버전에서도 적절한 크기로 잘 작동한다.

방법3) xib파일을 사용하지 않는 경우, viewDidLoad()에 아래를 추가한다.

self.view.frame =
[UIScreen mainScreen].bounds];


추가) 2012.12.21

iPhone4, iPhone5 Simulator

XCode 4.5에서 시뮬레이터로 실행하면 보통 iPhone 6.0 Simulator로 해서 Old iPhone의 시뮬레이터가 동작한다.
iPhone5에 맞추기 위해서는 

iOS Simulator 메뉴 > Hardware > Device >
iPad
iPad (Retina)
iPhone    iPhone older
iPhone (Retina 3.5-inch) iPhone 4.x
iPhone (Retina 4-inch) iPhone 5.x

로 선택해 사용이 가능하다.

처음에 당황스러웠는데, 시뮬레이터에 Home버튼이 없을 경우, 

Home키 : Shift + Command + H

를 이용하여 Home키 누르기와 두 번 실행하여 강제종료를 위한 더블클릭이 가능하다.


추가) 2013.01.04

iPhone5s가 곧 나올 것 같은데 이 버전은 iPhone5에서 가로로 좀 더 커져서 나올 예정이라고 한다.
Posted by 엔귤
2012. 9. 19. 08:51

회사달력의 공휴일만 가져오는 함수.

 

DATA: IT_HOLI LIKE ISCAL_DAY OCCURS 0 WITH HEADER LINE.

 

LV_ALTIME = DATE_TO – DATE_FROM.

CALL FUNCTION 'HOLIDAY_GET'

        EXPORTING

             HOLIDAY_CALENDAR           = 'E3'    “회사달력지정

             FACTORY_CALENDAR           = 'E3'    회사달력지정

             DATE_FROM                  = DATE_FROM  “FROM DATE

             DATE_TO                    = DATE_TO    “TO DATE

*    IMPORTING

*         YEAR_OF_VALID_FROM         =

*         YEAR_OF_VALID_TO           =

*         RETURNCODE                 =

         TABLES

              HOLIDAYS                   = IT_HOLI.  “공휴일만 저장된 ITAB.

*    EXCEPTIONS

*         FACTORY_CALENDAR_NOT_FOUND = 1

*         HOLIDAY_CALENDAR_NOT_FOUND = 2

*         DATE_HAS_INVALID_FORMAT    = 3

*         DATE_INCONSISTENCY         = 4

*         OTHERS                     = 5

 

    IF SY-SUBRC <> 0.

*     MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

    ELSE.

      DESCRIBE TABLE IT_HOLI LINES LINE.      “LINE = 공휴일수

      IF LINE <> 0.

        LV_ALTIME = LV_ALTIME - LINE.     “휴무일을 뺀 순수 작업일수

      ENDIF.

    ENDIF.

 

FROM DATE = TO DATE 인 경우 해당일자가 휴무일인지를 체크 할 수 있다.

  

특정일자의 달(月)의 마지막 일자를 가져오는 함수.

 

DATA LAST_DATE LIKE SY-DATUM.

 

CALL FUNCTION 'RP_LAST_DAY_OF_MONTHS'

  EXPORTING

    DAY_IN                  = SY-DATUM       “기준이 되는 임의의 일자

IMPORTING

LAST_DAY_OF_MONTH       = LAST_DATE      “해당월의 마지막 일자

* EXCEPTIONS

*   DAY_IN_NO_DATE          = 1

*   OTHERS                  = 2

          .

IF SY-SUBRC <> 0.

* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

ENDIF.

 
변수값 ALPHA CONVERSION 함수.

 

DATA: GV_MATNR(18),

TMP_MATNR LIKE MARA-MATNR.

 

CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT'

       EXPORTING

            INPUT  = TMP_MATNR        “ALPHA CONVERSION이 된 변수값

       IMPORTING

            OUTPUT = GV_MATNR.      “ALPHA CONVERSION이 안된 변수값

 

AND

 

CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'

       EXPORTING

            INPUT  = GV_MATNR        “ALPHA CONVERSION이 안된 변수값

       IMPORTING

            OUTPUT = TMP_MATNR.      “ALPHA CONVERSION이 된 변수값

 

OR

 

CALL FUNCTION 'FI_ALPHA_CONVERT'

       EXPORTING

         I_STRING       = GV_MATNR

       IMPORTING

         E_STRING       = TMP_MATNR.

 

 

GV_MATNR = ‘100060001’.

TMP_MATNR = ‘000000000100060001’.

 

  

INTERNAL TABLE을 TEXT FILE로 내리는 함수.

 

DATA ERFILE  LIKE RLGRAP-FILENAME VALUE 'C:\TEMP\SPEC.TXT'.

 

CALL FUNCTION 'WS_DOWNLOAD'

       EXPORTING

            FILENAME = ERFILE       “PC로 내려오는 파일 이름

            FILETYPE = 'DAT'        “DAT, DBF, ASC, BIN

       TABLES

            DATA_TAB = ITAB.        “텍스트로 내릴 ITAB.

 

OR

 

CALL FUNCTION 'DOWNLOAD'

       EXPORTING

            FILENAME = ERFILE       “PC로 내려오는 파일 이름

            FILETYPE = 'DAT'        “DAT, DBF, ASC, BIN

       TABLES

            DATA_TAB = ITAB.        “텍스트로 내릴 ITAB.

 

 

PC에 있는 텍스트 파일을 INTERNAL TABLE로 가져오는 함수

 

DATA: ED_FNAME LIKE RLGRAP-FILENAME VALUE 'C:\TEMP\OUT.TXT',

      ED_FTYPE LIKE RLGRAP-FILETYPE VALUE 'DAT'.

 

CALL FUNCTION 'WS_UPLOAD'

       EXPORTING

            FILENAME = ED_FNAME

            FILETYPE = ED_FTYPE    “DAT, DBF, ASC, BIN

       TABLES

            DATA_TAB = ITAB.     “텍스트파일의 내용을 가져오는 INTERNAL TABLE

 

OR

 

CALL FUNCTION 'UPLOAD'

       EXPORTING

            FILENAME = ED_FNAME

            FILETYPE = ED_FTYPE    “DAT, DBF, ASC, BIN

       TABLES

            DATA_TAB = ITAB.     “텍스트파일의 내용을 가져오는 INTERNAL TABLE

 

 

 

응용 프로그램 실행하는 함수.

 

CALL FUNCTION 'WS_EXECUTE'

       EXPORTING

            PROGRAM = 'C:\SAPPROD\PRT3000.EXE'.     “실행할 응용 프로그램

 

  

특정일자의 해당월의 마지막 일을 가져오는 함수

 

DATA TMP_LASTDAY(2).

 

CALL FUNCTION 'END_OF_MONTH_DETERMINE'

    EXPORTING

      DATUM = SY-DATUM         “기준이 되는 일자

    IMPORTING

      TT = TMP_LASTDAY         “해당월의 마지막 일(28,29,30,31)

    EXCEPTIONS

      OTHERS = 1.

 

  

PC에 있는 파일을 선택할 수 있는 파일선택 창 띄우는 함수

 

DATA: FILENAME(128).

 

CALL FUNCTION 'KD_GET_FILENAME_ON_F4'

  EXPORTING

    PROGRAM_NAME        = SYST-REPID

    DYNPRO_NUMBER       = SYST-DYNNR

*   FIELD_NAME          = ' '

*   STATIC              = ' '

*   MASK                = ' '

  CHANGING

    FILE_NAME           = FILENAME      “경로와 파일명이 들어가는 변수

* EXCEPTIONS

*   MASK_TOO_LONG       = 1

*   OTHERS              = 2

          .

IF SY-SUBRC <> 0.

* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

ENDIF.

 

  

하단의 상태바에 특정문자열을 표시해 주는 함수

 

CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'

       EXPORTING

            PERCENTAGE = SY-INDEX

            TEXT       = '데이터를 가져오는 중입니다…'.

 

LOOP문과 함께 사용하면 진행현황을 % 로 표시할 수 있다.

 

  

SAP 오피스의 메일박스에 메일 전송하는 함수

 

DATA : BEGIN OF MS_MAILOBJECT_CONT OCCURS 0.

          INCLUDE STRUCTURE MCMAILOBJ.

DATA : END OF MS_MAILOBJECT_CONT.

 

CLEAR : MS_MAILOBJECT_CONT.

REFRESH : MS_MAILOBJECT_CONT.

 

CONCATENATE '플랜트' WERKS ' 자재코드 ' MATNR

         ' 원가 생성작업을 해 주세요.'

         INTO MS_MAILOBJECT_CONT-OBJLINE.

 

  MOVE : '1' TO MS_MAILOBJECT_CONT-OBJNR,

         '1' TO MS_MAILOBJECT_CONT-OBJLEVEL,

         'RAW' TO MS_MAILOBJECT_CONT-OBJTYPE,

         '원가생성 요청' TO MS_MAILOBJECT_CONT-OBJNAM,

         '원가생성 요청' TO MS_MAILOBJECT_CONT-OBJDES.

  APPEND MS_MAILOBJECT_CONT.

 

  CALL FUNCTION 'MC_SEND_MAIL'

    EXPORTING

      MS_MAIL_SENDMODE         = 'B'

      MS_MAIL_TITLE            = '원가생성요청'

      MS_MAIL_DESCRIPTION      = '원가생성작업을 해주세요'

      MS_MAIL_RECEIVER         = 'ED03'

      MS_MAIL_EXPRESS          = ''      “ X=고속(받는사람의 작업화면에 창이 뜸)

TABLES

      MS_MAIL_CONT              = MS_MAILOBJECT_CONT

.

  IF SY-SUBRC <> 0.

* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

  ENDIF.

  

 

하나의 입력값을 받는 POPUP창 띄우는 함수

 

DATA ANSWER(1).

DATA VALUE1 LIKE SPOP-VARVALUE1.

 

CALL FUNCTION 'POPUP_TO_GET_ONE_VALUE'

    EXPORTING

      TEXTLINE1            = '서천 외주단가를 입력하세요.'

      TEXTLINE2            = '단가 입력후 계속을 클릭하면 입력.'

      TEXTLINE3            = '취소를 클릭하면 단가입력 취소.'

      TITEL                = '외주단가 입력'

      VALUELENGTH          = 10       “입력받을 길이

   IMPORTING

     ANSWER               = ANSWER     “선택버튼 종류

     VALUE1               = VALUE1.    “입력된 값

*  EXCEPTIONS

*    TITEL_TOO_LONG       = 1

*    OTHERS               = 2

   

사원번호를 가지고 해당 사원명 가져오는 함수

CALL FUNCTION 'RP_CHECK_PERNR'
       EXPORTING
            BEG    = SY-DATUM              
"오늘날짜
            PNR    = GV_PERNR              "사원번호
       IMPORTING
            NAME   = GV_NAME              
"사원명
       EXCEPTIONS
            OTHERS = 1.

문자열에서 특정문자(열) 변경 및 삭제

 

DATA: T_TEXT(30) VALUE '031-370-9164',

 

CALL FUNCTION 'STRING_REPLACE'
       EXPORTING
            PATTERN             = '-'  
" 변경할 문자열
            SUBSTITUTE          = ''    
" 변경될 문자열
*         MAX_REPLACES        = 0
*    importing
*         number_of_replaces  = numberofreplaces
       CHANGING
            TEXT                = T_TEXT    
" 문자열이 들어있는 문장
       EXCEPTIONS
            WRONG_STRING_LENGTH = 1
            OTHERS              = 2.

 

T_TEXT : ‘0313709164’

 

  

소수점이 있는 문자열을 DECIMAL TYPE으로 변환하는 함수

 

DATA: GV_TEXT(10),

GV_DECIMAL(10) TYPE P DECIMALS 3.

 

CALL FUNCTION 'CHAR_FLTP_CONVERSION'

EXPORTING

 STRING     = GV_TEXT        "CHAR 변수

        IMPORTING

          FLSTR     = GV_DECIMAL .    "DEC 변수

 

GV_TEXT : ‘2345.678’

GV_DECIMAL : 2345.678

 

  

두 일자사이의 개월 수를 계산하는 함수

 

CALL FUNCTION 'RH_PM_CONVERT_DATE_TO_MONTH'

  EXPORTING

    BEGDA               =  GV_BEGDA      “시작일자

    ENDDA               =  GV_ENDDA      “종료일자

IMPORTING

    MONTHS              =  ACT_MONTHS    개월수

* EXCEPTIONS

*   INVALID_BEGDA       = 1

*   OTHERS              = 2

          .

IF SY-SUBRC <> 0.

* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

*         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

ENDIF.

 

  

그래픽 구현

 

DATA: BEGIN OF ITAB_DATA OCCURS 0,

           DATANAME(15),

           QUANTITY1 TYPE I,

           QUANTITY2 TYPE I,

           QUANTITY3 TYPE I,

      END OF ITAB_DATA,

      BEGIN OF ITAB_OPTIONS OCCURS 0,

           OPTION(20),

      END OF ITAB_OPTIONS.

 

ITAB_DATA-DATANAME = '국내석건'.

ITAB_DATA-QUANTITY1 = 55.

ITAB_DATA-QUANTITY2 = 62.

ITAB_DATA-QUANTITY3 = 59.

APPEND ITAB_DATA.

ITAB_DATA-DATANAME = '산공생산'.

ITAB_DATA-QUANTITY1 = 35.

ITAB_DATA-QUANTITY2 = 52.

ITAB_DATA-QUANTITY3 = 44.

APPEND ITAB_DATA.

ITAB_DATA-DATANAME = '수출생산'.

ITAB_DATA-QUANTITY1 = 68.

ITAB_DATA-QUANTITY2 = 52.

ITAB_DATA-QUANTITY3 = 79.

APPEND ITAB_DATA.

 

CALL FUNCTION 'GRAPH_MATRIX_3D'

     EXPORTING

          COL1        = '1'

          COL2        = '2'

          COL3        = '3'

          TITL        = '매출금액'

     TABLES

          DATA        = ITAB_DATA

          OPTS        = ITAB_OPTIONS

     EXCEPTIONS

          OTHERS      = 1.

 

뒤에 붙은 ‘-‘부호를 앞으로 빼주는 함수

 

DATA GV_VALUE(5).

GV_VALUE = '1234-'.

 

CALL FUNCTION 'CLOI_PUT_SIGN_IN_FRONT'

  CHANGING

    VALUE         = GV_VALUE.

 

GV_VALUE “ ‘-1234’

 

  

POPUP 관련 함수들

 

POPUP_TO_CONFIRM_LOSS_OF_DATA - user가 delete명령같은 것을 실행할 때 dialog box생성한다.

POPUP_TO_CONFIRM_STEP
- user가 다음 단계로 실행을 원할 때 dialog box 를 생성한다.

POPUP_TO_CONFIRM_WITH_MESSAGE
- user가 수행중 어떤 특정한 결정을 내리는 부분에 있을 때,
                               정보제공 dialog box를 생성한다.


POPUP_TO_CONFIRM_WITH_VALUE
- user가 특정한 object로 작업을 수행하기를 원할 때
                             question box를 생성한다.


POPUP_TO_DECIDE
- user에게 radio button을 제공하여 결정하게 한다.

POPUP_TO_DECIDE_WITH_MESSAGE
-  user에게 분류된 text를 제공함으로써 결정하게 하는
                               dialog box를 생성한다.


POPUP_TO_DISPLAY_TEXT
- 두 줄로 된 dialog box를 생성한다.

POPUP_TO_SELECT_MONTH
- 달을 선택하게 한다.

POPUP_WITH_TABLE_DISPLAY
- 유저에게 선택한 table을 table line값과 함께
                          보여준다.

 

POPUP_TO_FILL_COMMAND_LINE – 입력값을 받을 수 있는 입력 필드가 생긴다.

 

 

  

문자열 자를 때 자르는 위치에 2BYTE문자가 있는지를 체크하는 함수

 

DATA: LV_LENGTH TYPE I.

 

CALL FUNCTION 'TRUNCATE_MULTIPLE_BYTE_STRING'

  EXPORTING

    STRING              = 'ABDC가1234'

    TARGET_LENGTH       = '5'

  IMPORTING

    USE_LENGTH          = LV_LENGTH

          .

LV_LENGTH 와 TARGET_LENGTH 에서 입력한 값이 일치하면 문제가 없고,

1이 작은 경우 2BYTE 문자가 걸림.

자르는 위치를 LV_LENGTH로 하면 문자가 깨지는 문제가 발생하지 않음.

 

OR

DATA: LV_O_STR(10).

 

CALL FUNCTION 'CUT_2BYTES_STRINGS'

  EXPORTING

    I_STR         = 'AB가나1234'

    I_LEN         = '5'

  IMPORTING

    O_STR         = LV_O_STR

          .

LV_O_STR : ‘AB가’

 

 

반올림, 올림, 버림을 쉽게 할 수 있는 함수

 

DATA: INPUT TYPE F,

      OUTPUT TYPE F,

      OUTPUT_N(5) TYPE N.

 

INPUT = '1276.65'.

 

CALL FUNCTION 'FIMA_NUMERICAL_VALUE_ROUND'

   EXPORTING

        I_RTYPE = ' '  "반올림

*        I_RTYPE = '+'  "올림

*        I_RTYPE = '-'  "버림

        I_RUNIT = '1'   “기준자리 수

        I_VALUE = INPUT

   IMPORTING

        E_VALUE_RND = OUTPUT.

 

OUTPUT_N = OUTPUT.

 

OUTPUT_N : ‘01277’

 

  

문자열에 있는 값이 숫자만으로 되어있는지 문자가 포함됐는지 체크하는 함수

 

DATA: STRING_1(20) TYPE C, STRING_1_TYPE(4) TYPE C,

      STRING_2(20) TYPE C, STRING_2_TYPE(4) TYPE C,

      STRING_3(20) TYPE C, STRING_3_TYPE(4) TYPE C.

 

STRING_1 = '12345678901234567890'.

STRING_2 = 'abcdefg우리나라만세z'.

STRING_3 = 'abcdAAA34557azzidfll'.

 

CALL FUNCTION 'NUMERIC_CHECK'

     EXPORTING

          STRING_IN = STRING_1

     IMPORTING

          HTYPE     = STRING_1_TYPE.

 

CALL FUNCTION 'NUMERIC_CHECK'

     EXPORTING

          STRING_IN = STRING_2

     IMPORTING

          HTYPE     = STRING_2_TYPE.

 

CALL FUNCTION 'NUMERIC_CHECK'

     EXPORTING

          STRING_IN = STRING_3

     IMPORTING

          HTYPE     = STRING_3_TYPE.

 

STRING_1_TYPE : NUMC

STRING_2_TYPE : CHAR

STRING_3_TYPE : CHAR

 

  

클립보드에 들어있는 내용을 가져오는 함수

 

DATA: BEGIN OF TAB OCCURS 1,

          TEXT(20) TYPE C,

      END OF TAB.

DATA  EMPTY(1).

 

CLEAR EMPTY.

REFRESH TAB.

FREE TAB.

 

CALL FUNCTION 'CLPB_IMPORT'

       IMPORTING

            EMPTY      = EMPTY

       TABLES

            DATA_TAB   = TAB

       EXCEPTIONS

            CLPB_ERROR = 01.

 

  

  

문자열로된 계산식의 계산값을 RETURN 하는 함수

 

DATA: AAA TYPE P.

 

CALL FUNCTION 'EVAL_FORMULA'

  EXPORTING

    FORMULA        = '(10+10)*10/10-7*(5+3)/7'

 IMPORTING

  VALUE          = AAA

          .

 

WRITE AAA.  => 12

Posted by 엔귤



This is a simple tutorial  to create "slide to unlock" feature.  As you may have guessed, we have to use UISlider. UISlider is an awesome object for many purposes - adjusting parameters of an object, or values of anything (size, amount, etc). But this time we will use it as a "Unlock Key". This type of control is useful when you have an app doing something and the user then puts the iPhone in his pocket while the app is still running. If we just use a normal UIButton to unlock, the user could accidentally touched it while the phone is in the pocket, and unlocked the screen of the app, accidentally. This is the same application as the normal iPhone lock feature.

DOWNLOAD THE SAMPLE CODE HERE

Ok, all we need in the project is a UISlider, a UIImageView and a UILabel. In .h, we declared them as follows:

IBOutlet UISlider *slideToUnlock;
IBOutlet UIButton *lockButton;
IBOutlet UILabel *myLabel;
IBOutlet UIImageView *Container;

The lockButton is just a control to enable you to enter the "Locked" status. Also we will be needing 3 methods to help us implementing the "Slide to Unlock" feature in our app.

-(IBAction)UnLockIt;
-(IBAction)LockIt;
-(IBAction)fadeLabel;

So, how do we go about implementing it. We need to think of the behaviour, of course. We want the user to slide the slider ball until the very end (right hand side), only then the screen be unlocked. Also, if the user slides half way or not until the very end, and let go (untouch) of the slider ball, we need to slide back the slider ball into initial position (value = 0, at the most left side). 

Translating that behaviour into code means: Since the behaviour depends on untouch action, therefore we will use the "Touch Up Inside" delegate of the UISlider. So we will connect the "Touch Up Inside" method to the UnLockIt method.

Let's take a look inside the UnLockIt method - we need to check the value of slider (which equals to the location of the slider ball), and translate the behaviour we stated above into codes:

-(IBAction)UnLockIt {

if (!UNLOCKED) {

if (slideToUnlock.value ==1.0) { // if user slide to the most right side, stop the operation 
// Put here what happens when it is unlocked

slideToUnlock.hidden = YES;
lockButton.hidden = NO;
Container.hidden = YES;
myLabel.hidden = YES;
UNLOCKED = YES;
} else { 
// user did not slide far enough, so return back to 0 position

[UIView beginAnimations: @"SlideCanceled" context: nil];
[UIView setAnimationDelegate: self];
[UIView setAnimationDuration: 0.35];
// use CurveEaseOut to create "spring" effect
[UIView setAnimationCurve: UIViewAnimationCurveEaseOut]; 
slideToUnlock.value = 0.0;

[UIView commitAnimations];

}

}

You notice that we also declare a global variable of type BOOL to check the state of the lock. If the slider ball is at the most right, the value is 1.0 (this is the default max value of a UISlider, you can change in IB if you want), then execute the method to unlock it, in this example, just to hide the slider, label and so on and display the Lock button. If it is not reaching to the right side, then we use CoreAnimation to animate the auto sliding of the slider ball back to initial position of 0.0 (which is at the most left hand side).

Note that I use the UIViewAnimationCurveEaseOut, this animation curve starts out very fast immediately and then slows down at the end. This is to make it similar to a spring reaction.

You also notice we added a label in there. Now, if you see the label in your iPhone, it fades out as you slide the slider towards the right side, we can accomplish this by tying the "Value Changed" delegate of the UISlider to the method fadeLabel as below:

-(IBAction)fadeLabel {

myLabel.alpha = 1.0 - slideToUnlock.value;

}

This is simple really. Whenever we move the slider ball from left to right, the value of the slider (that we named slideToUnlock), will increase from 0 to 1.0. But we want to change the label's alpha (opacity) from 1.0 to 0.0, therefore a simple invert is done by taking the max value of slideToUnlock and subtracting it to its current value. A better code would be to use

myLabel.alpha = slideToUnlock.maximumValue - slideToUnlock.value;

especially if you changed the maximum value to other than 1.0.

That's done with the behaviour of the slider. Now, what's left is just to customize the UISlider with custom slider ball. I also put a UIImageView (Container) at the back to align it nicely with the slider ball. You could also use the container image as the Slider's minimum and maximum track images. 

NOTE: Just a little note, the customizing of UISlider must be done at viewDidLoad, otherwise the slider won't be made custom for some reason.

So under viewDidLoad (or if you wish you can put it under applicationDidFinishLaunching), we put the customization code of the UISlider:

// I set the track images to be nothing (just a clear image)
UIImage *stetchLeftTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
UIImage *stetchRightTrack= [[UIImage imageNamed:@"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];

// this code to set the slider ball image
[slideToUnlock setThumbImage: [UIImage imageNamed:@"SlideToStop.png"] forState:UIControlStateNormal];
[slideToUnlock setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[slideToUnlock setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];

That's about it. Enjoy.

'I-Phone' 카테고리의 다른 글

[IOS] 잡지식모음  (0) 2011.02.18
[IOS] 유용한자료  (0) 2011.02.09
[IOS]UILabel 동적사이즈  (0) 2010.12.05
[IOS]오픈소스  (0) 2010.11.29
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
Posted by 엔귤
2011. 2. 18. 18:19

원문 : http://improgrammer.com/12

 

KT앱 대회 준비하면서 모은 자료들을 정리해서 올립니다.
거의 맥부기 카페 자료들이 대부분인데 한곳에 모아서 찾아보기 쉬우라고 올려봅니다.


-푸쉬  서버  개발  관련 자료-
이지 APNS 오픈 소스 라이브러리
http://www.easyapns.com/
구글 코드 APNS 오픈 소스
http://code.google.com/p/apns-php/
서버 튜토리얼
http://blog.boxedice.com/2009/07/10/how-to-build-an-apple-push-notification-provider-server-tutorial/


-label이나 textView에 현재 시간을 표시하고 싶습니다-
NSDate *t = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *timeStr = [formatter setDateFormat:@"HH:mm:ss"];
myLabel.text = timeStr;
...
[textView scrollRangeToVisible:NSMakeRange([textView.text length]-1, 1)];


-시뮬레이터 포토 라이브러리 자신의 이미지 추가 방법-
UIImage * sShot = [UIImage imageNamed:@"imageName.jpg"];
UIImageWriteToSavedPhotosAlbum(sShot, nil, nil, nil);


-네이게이션바 스타일 바꾸기-
http://cafe.naver.com/mcbugi/1241


-이미지 자르기 함수를 소개합니다. (UIImage)-

- (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
{
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/


-HTTP 라이브러리-
http://allseeing-i.com/ASIHTTPRequest/How-to-use


-json 관련-
라이브러리 http://code.google.com/p/json-framework/
json 투토리얼 http://iphonedevelopertips.com/networking/iphone-json-flickr-tutorial-part-1.html


-알럿 템플렛-
self.myAlertView = [ [UIAlertViewalloc]
initWithTitle:@"알림"
message:@"이메일을입력해주세요"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"확인", nil];
self.myAlertView.delegate = self;
[self.myAlertViewshow];


-푸쉬서버 구현을 위한 서버 인증서 pem 만들기-
애플 개발자 센터 apps ID 추가 (이때 와일드카드(*)는 사용하면 안됨)

키체인에서 개인 인증서 하나 만들어 애플 개발 센터에 등록

애플 개발센터에서 cert파일을 다운받아서 키체인으로 추가

키체인에서 내보내기로 p12파일로 저장

커맨드에서  p12파일을 pem파일로 변환
openssl pkcs12 -in quizers_dev_cert.p12 -out quizers_dev_cert.pem -nodes -clcerts


-전역변수를 사용해 보자...-
http://cafe.naver.com/mcbugi/55643


-JSON 2중 뎁스 이상 키 접근하기-
NSDictionary*feed =[self downloadPublicJaikuFeed];
// get the array of "stream" from the feed and cast to NSArrayNSArray*streams =(NSArray*)[feed valueForKey:@"stream"];
// loop over all the stream objects and print their titlesint ndx;
NSDictionary*stream;
for(ndx =0; ndx &lt; stream.count; ndx++){
        NSDictionary*stream =(NSDictionary*)[streams objectAtIndex:ndx];
        NSLog(@"This is the title of a stream: %@", [stream valueForKey:@"title"]); 
}


-배열 NSArray-
초기 데이터로 생성
NSArray *array = [[NSArray alloc] initWithobjects:추가할 객체들.. , nil];
 스트링으로 생성
NSArray *joins =(NSArray*)[result objectForKey:@"joins"];
길이 구하기
NSLog(@"Array size : %d " , sizeof(BUILDING_DATA) / sizeof(BUILDING_DATA[0]));


-NSString 클래스를 이용하여 문자을 넣자니 유니코드를 받아 초기화-
-(NSUInteger) UnicharLength:(const unichar*)str
{
unichar* pStr = (unichar*)str;
for( ; pStr[0] != nil ; pStr++ );
return (NSUInteger)(pStr - str);
}
[[NSString alloc] initWithCharacters:(원본문자열) length:[self UnicharLength:(원본문자열)]];


-랜덤 출력-
srandom(time(NULL));
value = random() % 100;
위처럼 하시면 0~99사이의 한수를 리턴합니다.
srandom(time(NULL)); 는 첨에 한번만 해주시면 됩니다.


-Code Sign error: Provisioning profile이 맞지 않을 때 변경 방법-
여러 장비에서 작업을 하거나 여러 프로젝트를 진행 중에 변경된 Provisioning profile이 적용되지 않아 Debug를 할 때 ”Code Sign error: Provisioning profile ‘3E6AA725-6534-46F8-B9CE-D19AC9FD854B’ can’t be found” 이런 오류가 발생하는 경우가 있는데요. 이럴 때 현재 사용중인 Provisioning Profiles로 프로젝트 세팅을 변경해주는 방법을 소개한 글(원문)이 있어서 공유합니다.

1. 실행중인 Xcode Project를 닫습니다.
2. Finder에서 프로젝트 폴더로 이동합니다.
3. 프로젝트 .xcodeproj 파일 선택하고 마우스 오르쪽 키를 눌러 '패키지 내용 보기'를 선택합니다.
4. 패키지 내용 보기를 통해 패키지 안에 있는 project.pbxproj 파일을 Xcode로 불러옵니다.
5. 검색을 통해 PROVISIONING_PROFILE 부분을 찾아 변경된 Provisioning profile 로 변경해줍니다.
6. 현재 Provisioning profile을 확인하려면 Organizer 창을 열어보면 알 수 있습니다.
7. Window > Organizer로 Organizer 창을 열고 왼쪽에 IPHONE DEVELOPMENT > Provisioning Profiles로 이동합니다.
8. 오른쪽에 있는 Profile Identifier를 복사해서 변경해주면됩니다.
9. 변경이 끝나면 project.pbxproj 저장하고 프로젝트를 열어 테스트합니다.


-아이폰 웹개발에서 디바이스 아이디 가져올수있나요?-
[[UIDevice currentDevice] uniqueIdentifier];



-Accessing Objects in a NSArray-
To access an object in an NSArray, you use the -objectAtIndex: method, as in the following example:NSArray *numbers;
NSString *string;

numbers = [NSArray arrayWithObjects: @"One", @"Two", @"Three", 
                                     nil];
string = [numbers objectAtIndex: 2];   // @"Three"

Of course, you have to be careful not to ask for an object at an index which is negative or bigger than the size of the array; if you do, an NSRangeException is raised (we'll learn more about exceptions in another tutorial).
To get the length of an array, you use the method -count, as in:
NSArray *numbers;
int i;

numbers = [NSArray arrayWithObjects: @"One", @"Two", @"Three", 
                                     nil];
i = [numbers count];   // 3


-상태바 제어-
안 보이게
[UIApplication sharedApplication].statusBarHidden = NO;

스타일
UIApplication *myApp = [UIApplication sharedApplication];
[myApp setStatusBarStyle:UIStatusBarStyleBlackOpaque];


-메모리 오버되어서 어플이 죽는 경우에 호출되는 이벤트??-

뷰컨트롤러 베이스로 작업을 한다면

- (void)didReceiveMemoryWarning

함수로 메모리가 위험할시에 위 함수를 핸들링하니 내부에 관련 대응할 처리를 구현해주면 됩니다.



-D-Day 구하기-
NSDate* date  = [NSDatedateWithNaturalLanguageString:@"2010-06-30"];
NSDate* d_day = [NSDatedateWithNaturalLanguageString:@"2010-12-31"];

NSDateComponents *dcom = [[NSCalendar currentCalendar]components: NSDayCalendarUnit
fromDate:date  
  toDate:d_day  
  options:0];

NSLog(@"day=%d",   [dcom day]);   // 184


-라디오 버튼이나 체크박스등을 찾지를 못하고  있는데-
Interface Builder 에서 library를 보시면 segmented control, switch가 보일겁니다.
말씀하시는 라디오버튼이나 체크박스는 없지만  
라디오버튼은 segmented control로 대체, 체크박스는 switch 로 대체하셔서 사용하시면 될듯합니다.


-책장 넘기기 효과-
UIView 를 하나 만들고 그 안에 UIImageView 를 만들었습니다.
이제 이미지뷰어의 내용을 채울때 책장을 넘기듯이 넘기는 방법입니다.

[UIView baginAnimations:@"stalker" context:nil]; <- stalker 는 UIView 의 이름입니다
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:stalker cache:YES];
[UIView setAnimationDuration:1.0];
imageView.image = [UIImage imageNAmed:이미지파일명];
[UIView commitAnimations];

이 걸 터치 이벤트나 이런곳에 삽입하면
책장을 넘기듯이 이미지의 전환이 일어납니다. 


-image를 fade out 효과-
[UIView beginAnimations:nil context:NULL];
[imageView setAlpha:0.0];
[UIView commitAnimations]; 


-UIView Animation 중복방지-
[UIView beginAnimations:nil context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveLinear]; 
....
[UIView setAnimationDelegate:self]; 
[UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)];
        [UIView commitAnimations];

이런 식으로 에니메이션을 만들었는데 간단하게 UIImageView를 한점에서 다른 한점으로 이동시킵니다.
근데 그래서 에니매이션이 끝나면 다시 또다른 다른 두 좌표로 해서 위의 코드가 실행되서 계속해서 UIImageView를 움직이게 하고 있습니다.

근데 질문은 1. setAnimationDidStopSelector 에서 에니매이션이 끝난것을 알기전에 강제로 에니메이션을 멈출수 있나요?
2. 제 경우에는 어떤 경우에 위 코드가 setAnimationDidStopSelector 가 호출되었을때 만 실행되는 것이 아니라 다른 부분에서도 호출하기도 합니다.  근데 문제는 동시에 위 코드가 중복되어서 호출되면 이상하게 작동해요.  그래서 꼭 위 코드를 실행(에니매이션을 commit 하기전에는 반드시 에니메이션을 강제로 멈추던지 아니면 다른 체크를 해야 할것 같은데.....  

혹시 방법이 있으면 부탁드립니다.

꾸벅~

답글 : 
[UIView setAnimationsEnabled:NO];
// 에니메이션을 종료 합니다. 


-일정시간 딜레이 후 함수 호출-
[self performSelector:@selector(playerStop) withObject:nil afterDelay :1.0f];

-(void) playerStop 
{
}


-개발 완료, 베타 테스팅용 Ad Hoc 배포-
http://cafe.naver.com/mcbugi/9042


-테이블뷰에 원격이미지를 넣을경우 스크롤이 느려지는 현상-
LazyTableImages 샘플http://developer.apple.com/iphone/library/samplecode/LazyTableImages/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009394
AsyncImageView 클래스 http://www.markj.net/iphone-asynchronous-table-image/


-테이블 뷰 섹션별로 이름 주기-
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if( section == 0 ) {
return@"발행한퀴즈";
} elseif( section == 1 ) {
return@"참여한퀴즈";
} else {
return@"진행중인퀴즈";
}
}


-정사각형으로 사진을 CROP 하고, 썸네일 크기에 맞게 리사이즈-
먼저, 출처는 다음 기사입니다.
http://tharindufit.wordpress.com/2010/04/19/how-to-create-iphone-photos-like-thumbs-in-an-iphone-app/ 
 
iPhone 사진앨범의 특징은 가로나 세로가 긴 이미지라 할지라도,
정사각형으로 사진을 CROP 하고, 썸네일 크기에 맞게 리사이즈 시킵니다.
 
위의 기사의 내용을 나름대로 보기 편하게(?) 수정을 했습니다.
 
함수명 - makeThumbnailImage
파라미터 - 원본 이미지, 리사이즈없이 CROP만 할지 여부, 리사이즈할 정사각형 한변의 길이
리턴값 - CROP 및 리사이즈된 이미지
 
- (UIImage*) makeThumbnailImage:(UIImage*)image onlyCrop:(BOOL)bOnlyCrop Size:(float)size
{
 CGRect rcCrop;
 if (image.size.width == image.size.height)
 {
  rcCrop = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
 }
 else if (image.size.width > image.size.height)
 {
  int xGap = (image.size.width - image.size.height)/2;
  rcCrop = CGRectMake(xGap, 0.0, image.size.height, image.size.height);
 }
 else
 {
  int yGap = (image.size.height - image.size.width)/2;
  rcCrop = CGRectMake(0.0, yGap, image.size.width, image.size.width);
 }
 
 CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rcCrop);
 UIImage* cropImage = [UIImage imageWithCGImage:imageRef];
 CGImageRelease(imageRef);
 if (bOnlyCrop) return cropImage;
 
 NSData* dataCrop = UIImagePNGRepresentation(cropImage);
 UIImage* imgResize = [[UIImage alloc] initWithData:dataCrop];
 
 UIGraphicsBeginImageContext(CGSizeMake(size,size));
 [imgResize drawInRect:CGRectMake(0.0f, 0.0f, size, size)];
 UIImage* imgThumb = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 [imgResize release];
 return imgThumb;
}

위 소스를 참고하시면, 이미지를 CROP 하는 방법이나, 이미지를 RESIZE 하는 방법을 참고하실수 있을겁니다.
 
사족을 붙이자면, 왜 Resize 할지 여부를 따로 분리 시킨 이유는 실제로 사용을 해보면 Resize 루틴에서
많은 CPU 부하가 걸립니다. 그래서 UIImageView 에  contentMode를 UIViewContentModeScaleAspectFit 로 설정해서
자체적으로 리사이즈를 하게 하는 방법이 비동기적으로 괜찮습니다. (물론.. 실제 Resize된 이미지가 아니므로 메모리적인 소비는 있습니다.)
 
많은 도움 되셨으면 좋겠네요 ^^


-사진찍을때  아래에서  올라오는  메뉴 UIActionSheet-
http://ykyuen.wordpress.com/2010/04/14/iphone-uiactionsheet-example/


-uibutton disable-
http://www.iphonedevsdk.com/forum/iphone-sdk-development/2499-uibutton-disable.html


-이미지  슬라이드  샘플-
http://lievendekeyser.net/index.php?module=messagebox&action=message&msg_id=1351


-커버플로우  라이브러리-
http://apparentlogic.com/openflow/


-Xcode3.2.3과 SDK4로 업그레이드 후, 기존 앱 업그레이드 하는 법-
XCode3.2.3 과 SDK4로 버전업한 후, 기존 앱을 업그레이드 할 때 간단한 Tip 입니다.
1. XCode3.2.3과 SDK4로 업그레이드 한다. 별도로 기존 XCode 3.1 버전을 따로 보관할 필요가 없습니다.
2. 기존 앱을 새 XCode3.2.3에서 연다.
3.Group & Files를 right click -> Get Info 후
  3-1.General Tab 에서
Project Format 을 Xcode 3.2-compatible 로 바꾼다.
 3-2.Build Tab 에서
 Base SDK를 iPhone Device 4.0(배포시), 혹은 iPhone Simulator 4.0(테스트시) 로 바꾼다
 iPhone OS Deployment Target 을 iPhone OS 3.0 (즉 지원하고자 하는 하위버전으로) 로 바꾼다.
이렇게 하시면 됩니다.


-객체 타입 비교-
if ( [a isKindOfClass:b] )


-문자열 비교-
NSString *strText = idField.text;
if([srText isEqualToString:@"mihr01"])
....
else if([srText isEqualToString:@"mihr02"])
....
else
...
이렇게 하셔도 되고요 완전 같은 스트링이 아니라
 
포함된것을 찾으려면
if([strText rangeOfString:@"mihr01"].length) 


-탭뷰에 스타일시트를 붙일때-
UIActionSheet *popupQuery = [[UIActionSheetalloc]
initWithTitle:nildelegate:self
cancelButtonTitle:@"취소"
destructiveButtonTitle:nil
otherButtonTitles:@"사진찍기", @"기존의사진선택", nil];
popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
QuizersAppDelegate *appDelegate = (QuizersAppDelegate *)[[UIApplicationsharedApplication] delegate];
[popupQuery showInView:appDelegate.window];


-스크롤  밀어서  데이터  리플래쉬  하기-
소스코드
http://github.com/facebook/three20/tree/master/samples/TTTwitter/
설명
http://www.drobnik.com/touch/2009/12/how-to-make-a-pull-to-reload-tableview-just-like-tweetie-2/


-테이블뷰 위에 검색창 붙이는 방법-
테이블뷰 위에 검색창 넣으신 후에, viewDidLoad 메서드 부분에 [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO];해주시면 처음 보여질 때는 검색창이 안 보이다가 밑으로 땡기면 나타나게 됩니다.


-네트워크  연결  됐는지  확인 Reachability-
http://www.raddonline.com/blogs/geek-journal/iphone-sdk-testing-network-reachability/
http://theeye.pe.kr/entry/how-to-check-network-connection-on-iphone-sdk



-아이폰 강제종료 버튼 이벤트-
아래 메소드가 어플이 종료될 때 수행되는 함수입니다.
종료될 때에 각종 리소스들을 Free시킬 경우에 사용됩니다.
참고하시면 될 듯 합니다~
 - (void)applicationWillTerminate:(UIApplication  *)application



-크랙 방지 클래스-
http://cafe.naver.com/mcbugi/11661



-어플을 강제 종료하는 API 는 아이폰에서 제공하지 않는다?-
http://cafe.naver.com/mcbugi/11803



-탭바 클릭시 바로 UISearchBar 클릭되도록 할려면 어떻게 해야 하나요?-
UISearchBar가 first responder가 되게 하면 됩니다.
[searchBarObj becomeFirstResponder];



-UITextField 입력값 체크하기 : 문자열 길이, 숫자여부 체크-

헤더(.h)에 UITextFieldDelegate 선언

@interface 클 래스명 : UIViewController <UITextFieldDelegate>



구현부(.m)에 다음 메쏘드를 구현하면 됨

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 

//return NO하면 입력이 취소됨
//return YES하면 입력이 허락됨
//textField 이용해서 어느 텍스트필드인지 구분 가능

//최대길이

int maxLength = 128;

NSString *candidateString;

NSNumber *candidateNumber;


//입력 들어온 값을 담아둔다

candidateString = [textField.text stringByReplacingCharactersInRange:rangewithString:string];


if(textField == IDField) {
maxLength = 8;
} else if(textField == AgeField) {
//숫자여부 점검

//length가 0보다 클 경우만 체크
//0인 경우는 백스페이스의 경우이므로 체크하지 않아야 한다

if ([string length] > 0) {

//numberFormatter는 자주 사용할 예정이므로 아래 코드를 이용해서 생성해둬야함

//numberFormatter = [[NSNumberFormatter allocinit];

//[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];


//numberFormatter 를 이용해서 NSNumber로 변환

candidateNumber = [numberFormatter numberFromString:candidateString];


//nil이면 숫자가 아니므로 NO 리턴해서 입력취소

if(candidateNumber == nil) {

return NO;

}


//원 래 문자열과 숫자로 변환한 후의 값이 문자열 비교시 다르면

//숫자가 아닌 부분이 섞여있다는 의미임

if ([[candidateNumber stringValuecompare:candidateString] != NSOrderedSame) {

return NO;

}


maxLength = 2;

}

}

//길이 초과 점검

if ([candidateString length] > maxLength) {

return NO;

}


return YES;

}

http://cafe.naver.com/mcbugi/37651



-How to split string into substrings on iPhone?-
http://stackoverflow.com/questions/594076/how-to-split-string-into-substrings-on-iphone



-메모리 누수-
http://cafe.naver.com/mcbugi/64257


-디바이스 가로 세로 상태-
UIDeviceOrientationIsLandscape([UIDevicecurrentDevice].orientation) ?


-UITextField 에 자동 포커스 주기-
키보드 올리면서 커서를 넣을때는 아래방법을 이용하시면 됩니다.
[textField becomeFirstResponder]; 
참고로 이건 커서를 빼면서 키보드를 내리실때 사용하시면 되구요...
[textField resignFirstResponder]; 


-홈버튼이 눌렸을 때도 텍스트뷰 내용을 저장하려면 어떻게 해야할까요?-
- (void)applicationWillTerminate:(UIApplication *)application / Application Delegate 메서드 부분에 구현하시면 되지않을가요? 


-3.2 4.0  동영상  플레이-
http://iphonedevelopertips.com/video/getting-mpmovieplayercontroller-to-cooperate-with-ios4-3-2-ipad-and-earlier-versions-of-iphone-sdk.html


-한글완성형(EUC-KR)을 iPhone/Mac에서 사용할 수 있는 언어셋으로 변환하기-
http://blog.backpackholic.tv/160


-인터페이스 함수들을 편하게 가져오는 방법-
http://code.google.com/p/xcode-auto-assistant/


-#pragma mark로 코드 쉽게 구분하기-
http://cafe.naver.com/mcbugi/64408


-os4에서 applicationWillTerminate가 안먹어서 알게된것-
os4에서 applicationWillTerminate: 가 안먹어서 삽질하다가 알아낸 결과입니다.
뒷북 인지는 모르지만 혹시 모르시는 분을 위해서 적어봅니다.
os3.x 에서는 홈버튼을 한번만 누르면 applicationWillTerminate 가 아주 잘 호출됩니다.
하지만 os4 에서는 홈버튼을 한번만 누르면 
applicationDidEnterBackground 가 호출됩니다.
os4 에서 멀티태스킹을 위해서 좀 바뀌었습니다.
os4에서도 홈버튼 한번 누를때 applicationWillTerminate 가 호출되게 하려면
info.plist 에서 'Application does not run in background' 이 속성을 추가해주면 됩니다.
위 속성이 없으면 기본적으로 멀티태스킹이 되는걸로 간주합니다. (진짜 멀티태스킹은 아니지만)
위 속성이 없을때 호출되는 메소드를 실험해 봤습니다.
-----------------------------------------------------------------
처음 어플을 실행시키면
     didFinishLaunchingWithOptions, 
applicationDidBecomeActive 
이 호출되고
홈버 튼을 한번 만 누르면
applicationWillResignActive, 
applicationDidEnterBackground
호출되면서 어플이 종료되고
이상태에서 다시 어플을 실행시키면
applicationWillEnterForeground, 
applicationDidBecomeActive 
호출됩니다.
홈버튼을 두번 누르면
applicationWillResignActive
이 호출됩니다.
----------------------------------------------------------------
'Application does not run in background' 을 체크하면
홈버 튼을 한번만 누르면 applicationWillTerminate 를 호출합니다.
'근데 속성 체크 안했을때 applicationWillTerminate 는 호출이 안되는건지 궁금하네요.
아시는 분 좀 알려주세요.

답글 : 
Applicationwillterminate함수 대신에 applicationDidENterBAckground 사용하라고하네여 이곳에서 공유자원해제나 사용자데이타 저장,타이머 무효화,어플상태정보등 저장을 하라고 합니다. http://cafe.naver.com/mcbugi/65497


-COCOS2D 번개 효과-
http://www.cocos2d-iphone.org/forum/topic/370


-iPhone 4.0 호환 키보드에 버튼 or 뷰 붙이기-
기존꺼에 비해 약간 수정되 었을뿐입니다....
하지만 -_-이거 찾느라 ㅠㅠ;; 

3.1.x에서는 windows 서브뷰에 항상 키보드 뷰가 있었지만 ...
4.0 부터는 windows 에 항상 있는게 아니고, 키보드를 불렀을때 -_- 붙어서 오더라고요.. 그래서

Done 버튼 붙이는 예제 입니다. (Number 패드에)

아래 액션을 Text필드의 BeginTouched 에 연결 시킵니다.
 // 키보드가 나왔을때랑 사라질때의 이벤트를 잡아냅니다.
//3.1.X 에서는 UIKeyboardWillShowNotification 으로 잡지만
// 4.0 때문에 --; DidShow로 잡아줬습니다.
//그래야 윈도우에 키보드가 있더라고요 ;;;
-(IBAction)FieldTouched{
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
}

// 키보드가 나왔을때 Done 버튼 붙여주기 
- (void)keyboardWillShow:(NSNotification *)note {  
    
    UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    doneButton.frame = CGRectMake(0, 163, 106, 53);
    doneButton.adjustsImageWhenHighlighted = NO;
    [doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
    [doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
    [doneButton addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventTouchUpInside];

    //3.1.x 와 4.0 호환 키보드 붙이기
    for( UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows] ){
        for( UIView *keyboard in [keyboardWindow subviews] ){
            NSString *desc = [keyboard description];
            if( [desc hasPrefix:@"<UIKeyboard"]==YES ||
               [desc hasPrefix:@"<UIPeripheralHostView"] == YES ||
               [desc hasPrefix:@"<UISnap"] == YES )
            {
                [keyboard addSubview:doneButton];
            }
        }
    }
    
}

// 키보드가 없어질때 Done 버튼을 삭제 합니다.
- (void)keyboardWillHide:(NSNotification *)note {  
    
    for( UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows] ){
        for( UIView *keyboard in [keyboardWindow subviews] ){
            NSString *desc = [keyboard description];
            if( [desc hasPrefix:@"<UIKeyboard"]==YES ||
               [desc hasPrefix:@"<UIPeripheralHostView"] == YES ||
               [desc hasPrefix:@"<UISnap"] == YES )
            {
                for(UIView *subview in [keyboard subviews])
                {
                    [subview removeFromSuperview];
                }
                
            }
        }
    }
}

도 움 되시길 바랍니다 ;)
http://cafe.naver.com/mcbugi/62349


-배열내 숫자 값 비교해서 정렬하기-
만약에 객체내의 인스턴스를 키로 정렬할 경우에는 NSSortDescriptor 를
쓰시면 됩니다.
아래는 name으로 정렬한 예입니다.

@interface Test :
NSObject {
NSString *name;
double distance;
}
@property
(nonatomic, retain) NSString *name;
@property double
distance;
@end

@implementation Test
@synthesize name, distance;
@end


아 래는 사용방법입니다.
       Test *t1 = [[Test alloc] init];
Test *t2 = [[Test alloc] init];
Test *t3 = [[Test alloc] init];
[t1 setName:@"마바사"];
[t2 setName:@"아자차"];
[t3 setName:@"가나다"];
[t1 setDistance:1.2];
[t2 setDistance:2.5];
[t3 setDistance:0.5];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:t1];
[array addObject:t2];
[array addObject:t3];
[t1 release];
[t2 release];
[t3 release];
// 이름순으로 정렬
NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCompare:)];
[array sortUsingDescriptors:[NSArray arrayWithObjects:nameSort, nil]];
[nameSort release];
for(Test *t in array) {
NSLog(@"%@ %f", [t name], [t distance]);
}
[array removeAllObjects];


------[결 과]------
2010-07-12 17:46:13.117 Sort[5070:20b] 가나다 0.500000
2010-07-12 17:46:13.125 Sort[5070:20b] 마바사 1.200000
2010-07-12 17:46:13.130 Sort[5070:20b] 아자차 2.500000


p.s. distance로 정렬하고자 한다면 
NSSortDescriptor *distanceSort = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
nameSort 대신 distanceSort를 넣으시면 됩니다.
http://cafe.naver.com/mcbugi/65873


-[TIP] 시뮬레이터 사진앨범에 사진넣기-
1) 시뮬레이터를 실행시킵니다.

2) 맥에서 포토라이브러리에 넣을 사진을 시뮬레이터로 Drag&Drop 합니다.

3) 그러면, 사파리가 열리면서 Drag한 이미지가 표시가 될겁니다.

4) 그 표시된 이미지를 마우스로 꾸~~~~~~욱 눌러줍니다.

5) 그러면, 메뉴가 뜨면서 이미지를 저장할건지 복사할건지를 묻습니다.

6) 이미지 저장을 누릅니다.

7) 이제 시뮬레이터의 사진앨범에 가 보시면 아까 저장한 사진이 들어가있을겁니다.

'I-Phone' 카테고리의 다른 글

[IOS]How To Do: Slide to Unlock  (0) 2011.03.29
[IOS] 유용한자료  (0) 2011.02.09
[IOS]UILabel 동적사이즈  (0) 2010.12.05
[IOS]오픈소스  (0) 2010.11.29
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
Posted by 엔귤

출처 :http://alones.kr/tag/nsurlrequest


[iPhone][Tutorial #3] URL Loading System – Http로 이미지를 받아서 보이기 (HttpManager 이용)

iPhone은 NSURLRequest와 NSURLConnection 를 이용해서 http request와 response를 쉽게 처리할 수 있게 해준다.

첫 아이폰 앱이었던 Make Num을 개발할 때 http request/response를 위한 유틸 클래스를 만들었던 것을 이용해, http request로 이미지를 받아서 보여주는 것에 대해 다루는 튜토리얼이다.

Make Num 때에는 Ranking 서버에서 점수와 해당 정보를 받아오는 것을 string으로 받아올 때 사용했다.

.

App to Make in this tutorial

이번 튜토리얼에서 만들 앱은 아래 Picasa에 있는 이미지를 받아서 UIImageView에 뿌려주는 간단한 앱이다.

http://lh4.ggpht.com/_85hIOLhClFE/SpAB03RUZtI/AAAAAAAAFgs/VdhbDuH8riQ/sample.png

Simulator에서 실행시킨 모습은 아래와 같다 (싱가폴에서 찍은 사진이다. ㅋ).

그림 9 by you.

.

HttpManager

HttpManager는 URL Loading System Guide 문서를 보고 만든 Class이다.

URL을 String으로 주면, 해당 주소의 웹페이지를 읽어서 NSMutableData로 전달해준다. 이 Tutorial의 경우는 웹 페이지가 image이기 때문에 NSMutableData로 UIImage를 만들면 되고, 페이지가 문자열일 경우는 NSString을 만들어서 처리하면 될 것이다.

HttpManager를 사용하기 위해서는 Caller가 HttpManagerDelegate를 Adopt 하게 했다. Http request 시 callback 되는 method들을 처리해주기 위해서이다.

HttpManager를 들여다보자.

.

HttpManager Class 선언 부

HttpManagerDelegate를 받은 Caller를 받기 위한 delegate와 response data를 받기 위한 received data를 가지고 있다.

01 @protocol HttpManagerDelegate;
02  
03 @interface HttpManager : NSObject {
04  
05     id  delegate;
06  
07     NSMutableData *receivedData;
08 }
09  
10 @property (nonatomic, assign) id delegate;
11 @property (nonatomic, retain) NSMutableData *receivedData;

.

HttpManagerDelegate protocol

HttpManagerDelegate protocol은 http request 시 request가 완료되었을 때와 실패했을 때 callback 되는 method들을 정의하고 있다. 그 외 request 시 callback 되는 NSURLConnectionDelegate의 connection method들은 내부적으로 처리했다.

1 @protocol HttpManagerDelegate
2  
3 -(void)connectionDidFail:(HttpManager*)aHttpManager;
4 -(void)connectionDidFinish:(HttpManager*)aHttpManager;

.

[HttpManager initWithUrl: delegate:]

HttpManager를 initWithUrl로 init 하면 바로 주어진 url의 loading을 시작한다. 즉, url에 대해서 NSURLRequest를 만들고, NSURLConnection 생성해서 loading을 시작한다. 여기서 NSString의 URL을 [NSString stringByAddingPercentEscapesUsingEncoding:]에 NSUTF8StringEncoding을 지정해서 encoding하는 것을 잊지 말아야 한다. 공백이나 특수 문자 등을 ‘%’를 써서 encoding 해준다.

01 -(id)initWithUrl:(NSString*)aURL delegate:(id)aDelegate {
02  
03     if( self = [super init] ) {
04  
05         // delegate
06         self.delegate = aDelegate;
07  
08         // URL string을 아래와 같이 %가 필요한 곳에 붙여주는 encoding 해줘야한다.
09         NSString *escapedUrl = [aURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
10  
11         // create the request
12         NSURLRequest *aRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:escapedUrl]
13                                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
14         // create the connection with the request
15         // and start loading the data
16         NSURLConnection *aConnection=[[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
17         if (aConnection) {
18             // Create the NSMutableData that will hold
19             // the received data
20             // receivedData is declared as a method instance elsewhere
21             receivedData = [[NSMutableData data] retain];
22         else {
23             // inform the user that the download could not be made
24             // [todo] error
25         }
26     }
27  
28     return self;
29 }

.
[HttpManager connectionDidFinishLoading:]

HttpManager의 다른 method들은 간단하며 HttpManagerDelegate를 adopt 한 caller의 해당 method를 불러주기 위해 caller가 해당 method를 가지고 있는지 체크하는 코드를 보라고 connectionDidFinishLoading method 코드를 보여준다. Caller의 connectionDidFinishLoading method가 불리면 Caller는 HttpManager의 receivedData를 받아서 사용하면 된다.

01 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
02  
03     if( [self.delegate respondsToSelector:@selector(connectionDidFail:)]) {
04         [self.delegate connectionDidFinish:self];
05     }
06  
07     [connection release];
08     if( receivedData != nil) {
09         [receivedData release];
10         receivedData = nil;
11     }
12 }

.

UI 부분 완성하기

이 번에도 IB (Interface Builder) 없이 간단하게 UI를 만들겠다.

시나리오는 아래와 같다.

1. applicationDidFinishLaunching 에서 UIImageView, UIActivityIndicatorView를 생성하고 Indicator Animation을 start한 후 HttpManager에 Picasa의 이미지를 가져오게 http request를 요청한다.

2. HttpManagerDelegate의 connectionDidFinish 가 callback 되면 HttpManager의 receivedData를 가져와서 UIImage를 만들고 UIImageView에 넣어준다.

.

URLLoadingSystem_imageAppDelegate class 선언

URLLoadingSystem_imageAppDelegate는 HttpManagerDelegate를 adopt해서 아래와 같다.

01 #import
02 #import "HttpManager.h"
03  
04 @interface URLLoadingSystem_imageAppDelegate : NSObject  {
05     UIWindow *window;
06  
07     UIImageView *imageView;
08     UIActivityIndicatorView *indicator;
09  
10     HttpManager *httpManager;
11     NSMutableData *receivedData;
12 }
13  
14 @property (nonatomic, retain) IBOutlet UIWindow *window;
15 @property (nonatomic, retain) UIImageView *imageView;
16  
17 -(void)getImageFrom:(NSString*)url;
18  
19 @end

.

UIApplicationDelegate의 applicationDidFinishLaunching

위에서 설명한 것과 같이 UIImageView를 생성해서 UIWindow에 add하고 UIActivityIndicatorView를 생성해서 UIImageView에 add 후 animation을 시작하고 HttpManager를 picasa url로 init해서 URL Loading을  시작한다.

01 - (void)applicationDidFinishLaunching:(UIApplication *)application {   
02  
03     // Override point for customization after application launch
04     // create UIImageView
05     imageView = [[UIImageView alloc] initWithFrame:window.frame];
06     [window addSubview:imageView];
07  
08     // image를 받을 때까지 indicator를 동작시킨다.
09     indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake( window.frame.size.width/2 - 20, window.frame.size.height/2-20, 40, 40)];
10     indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
11     [imageView addSubview:indicator];
12     [indicator startAnimating];
13  
14     // 아래 url에서 이미지를 가져와서 UIImageView에 보여준다.
16  
17     [window makeKeyAndVisible];
18 }
19  
20 -(void)getImageFrom:(NSString*)url {
21     if( httpManager ) {
22         [httpManager release];
23         httpManager = nil;
24     }
25  
26     httpManager = [[HttpManager alloc] initWithUrl:url delegate:self];
27 }

.

HttpManagerDelegate의 connectionDidFinish를 adopt

connectionDidFinish: 는 URL Loading이 완료되었을 때 callback 된다. 여기서 HttpManager의 receivedData를 가져와서 아래와 같이 UIImage를 생성해서 UIImageView에 넣어주면 완료된다.

1 #pragma mark HttpManagerDelegate
2 -(void)connectionDidFinish:(HttpManager*)aHttpManager {
3     [indicator stopAnimating];
4  
5     receivedData = httpManager.receivedData;
6     imageView.image = [[UIImage alloc] initWithData:receivedData];
7 }

.

Http Request Fail 처리

HttpManagerDelegate의 connectionDidFail은 Http Request가 실패했을 때 callback 된다. 아래와 같이 사용자에게 실패했다는 메시지를 UIAlertView로 보여준다.

1 -(void)connectionDidFail:(HttpManager*)aHttpManager {
2     [indicator stopAnimating];
3  
4     UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Fail" message:@"Couldn't connect"delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil] autorelease];
5     [alertView show];
6 }

.

Source Code

이 Tutorial의 코드는 아래에서 받을 수 있다.

Download Sample Code

.


[iPhone] NSURLRequest로 받은 response에서 Http header를 가져오기 – Accessing HTTP Headers From An NSURLRequest

  0 Comments and 0 Reactions

iPhone에서 http request/response는 아주 쉽고 여러 가지 용도로 잘 사용할 수 있게 제공되어 있다.

Mobile Orchard에 보니 response 받는 Http의 header를 가져오는 것에 대해서 포스트가 있어서 포스팅한다.

답은 NSHTTPURLRespones의 allHeaderFields method를 이용하는 것이다.

Synchronous request의 코드는 아래와 같고,

1 NSURL *url = [NSURL URLWithString:@"http://www.mobileorchard.com"];
2 NSURLRequest *request = [NSURLRequest requestWithURL: url];
3 NSHTTPURLResponse *response;
4 [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
5 NSDictionary *dictionary = [response allHeaderFields];
6 NSLog([dictionary description]);

Asynchronous request는 connection:didReceiveResponse:를 이용해서 아래와 같다.

1 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
2     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
3     NSDictionary *dictionary = [httpResponse allHeaderFields];
4     NSLog([dictionary description]);
5 }

Ref: Accessing HTTP Headers From An NSURLRequest


Posted by 엔귤
2011. 2. 9. 10:01
 

출처 : http://xguru.net/622

아이폰 개발시 도움이 되는 각종 팁 , 튜토리얼, 소스코드 링크 모음입니다. 제가 주로 트위터를 통해서 공개한 것들입니다만, 워낙 간헐적으로 트위팅 한듯해서 좀더 링크를 모아서 포스팅 합니다. 한글판 앱스토어 리뷰 가이드라인은 아이폰 앱 개발자분들은 꼭 한번 읽어보셔야 합니다.


'I-Phone' 카테고리의 다른 글

[IOS]How To Do: Slide to Unlock  (0) 2011.03.29
[IOS] 잡지식모음  (0) 2011.02.18
[IOS]UILabel 동적사이즈  (0) 2010.12.05
[IOS]오픈소스  (0) 2010.11.29
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
Posted by 엔귤

아이폰 개발을 하다보면 UILabel안에 들어가는 내용의 분량에따라 UILabel의 사이즈를 동적으로 UILabel의 크기를 조정해야 할 필요가 있을때가 있습니다.
01.float resultBodyWidthSize = 320.0f; //UILabel의 Width
02.UILabel *_resultBody;
03.NSMutableString *resultText = [[NSMutableString alloc] initWithString:@"동적사이즈의 UILabel구하기"];
04.  
05._resultBody = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, resultBodyWidthSize , 0)];
06._resultBody.text    = resultText;
07._resultBody.lineBreakMode = UILineBreakModeWordWrap;
08._resultBody.font = [UIFont systemFontOfSize:resultBodyFontSize];
09.          
10.CGSize suggestedSize = [resultText sizeWithFont:_resultBody.font constrainedToSize:CGSizeMake(resultBodyWidthSize, FLT_MAX) ineBreakMode:UILineBreakModeWordWrap];
위와 같은 코드를 사용하면 CGSize를 구할 수 있습니다.
1.//CGRect를 이용하여 UILabel를 Resizing
2.[_resultBody setFrame:CGRectMake(0, 90, 320, suggestedSize.height)];
그리고 구해진 CGSize를 UILabel에 적용시키면 동적인 사이즈의 UILabel을 만들 수 있습니다.

'I-Phone' 카테고리의 다른 글

[IOS] 잡지식모음  (0) 2011.02.18
[IOS] 유용한자료  (0) 2011.02.09
[IOS]오픈소스  (0) 2010.11.29
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
[i-Phone]static libray  (0) 2010.10.27
Posted by 엔귤
2010. 11. 29. 16:24

공부를 하다 보면 책에 나오는 간단 간단한 소스가 아닌 전체 프로그램에 대한 소스를 보고 싶어질 때가 있습니다.
그래서 자료를 찾아 보았습니다. 참고하세요.
 
<무인코딩 동영상 플레이어 VLC iPhone, iPad>
 
<web server>
 
<bar code, QR code>
 
<push notification service 관련 provider>

<web 게시판과 연동>

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

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

<map>

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

<sqlite>

<계산기>

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

<facebook>

<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/ (고스톱)

 

<google toolbox>

http://code.google.com/p/google-toolbox-for-mac/


<택배>

 

<이미지 프로세싱>

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/

'I-Phone' 카테고리의 다른 글

[IOS] 유용한자료  (0) 2011.02.09
[IOS]UILabel 동적사이즈  (0) 2010.12.05
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
[i-Phone]static libray  (0) 2010.10.27
[iphone]sqlite  (0) 2010.10.20
Posted by 엔귤
1. 우선 주소록 연동을 위해 AddressBook.framework를 추가하시구요.
좌측의 framework 폴더에서 우클릭 -> Add -> Existing Frameworks... -> AddressBook.framework 추가

2. 관련 헤더 파일을 import 시킵니다.

#import <AddressBook/AddressBook.h>


3. 주소록 정보를 가져옵니다.

ABAddressBookRef addressbook = ABAddressBookCreate();

CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressbook);

ABRecordRef person = CFArrayGetValueAtIndex(people, row);

  * 주소록에 저장되어 있는 이름을 TableView에 뿌려주고 사용자가 선택한 row를 이용하여 ABRecordRef에 저장합니다.

4. 주소록에 저장된 전화번호와 전화번호의 Label을 읽어옵니다.

ABMultiValueRef *phones = (ABMultiValueRef*)ABRecordCopyValue(person, kABPersonPhoneProperty);


for(i = 0; i < ABMultiValueGetCount(phones); i++) {

// 각각의 전화번호에 대한 Label을 읽어옵니다.(ex: 집, 직장, 등..)

NSString *phoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phones, i));

// 실제 전화번호 값을 읽어옵니다.(ex: 010-1111-1111, 02-2222-2222, 등..)

NSString *phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);

}



'I-Phone' 카테고리의 다른 글

[IOS]UILabel 동적사이즈  (0) 2010.12.05
[IOS]오픈소스  (0) 2010.11.29
[i-Phone]static libray  (0) 2010.10.27
[iphone]sqlite  (0) 2010.10.20
xcode 단축키  (0) 2010.10.20
Posted by 엔귤
2010. 10. 27. 21:50

'I-Phone' 카테고리의 다른 글

[IOS]오픈소스  (0) 2010.11.29
[I-Phone] 주소록 Label읽어오기  (0) 2010.11.26
[iphone]sqlite  (0) 2010.10.20
xcode 단축키  (0) 2010.10.20
NSString 문자열 조작  (0) 2010.09.27
Posted by 엔귤
이전버튼 1 2 이전버튼