본문 바로가기

PDA&Mobile

아이폰 앱 개발 팁(11) : Head First iPhone Development #2

* 본 포스트는 Blog.MissFlash.com에서 작성한 것으로, 원문 저작자의 동의없이 마음대로 퍼가실 수 없습니다. 포스트의 내용이 마음에 드시면 링크를 이용해주시면 감사하겠습니다.

> Head First iPhone Development #2

Chapter 2. iPhone app patterns - Hello @twitter!

App develop process
  1. Determine app layout
  2. Build the GUI
  3. Figure out how to use the controls
  4. Handle the data
  5. Send output to Twitter

The life of a root view
  1. Like in most other languages, main(...) gets called first.
  2. Main kicks off a Cocoa Touch Application.
  3. MainWindow.xib contains the connections for our application.
  4. The Cocoa Touch framework creates our custom view from the InstaTwitViewController.xib.
  5. When events occur with components, methods are invoked on our controller instance.

Development process
  1. First, declare that the controller conforms to both protocols(UIPickerViewDataSource, UIPickerViewDelegate).
  2. Next, add Mike's activities and feelings to the implementation file.
  3. The datasource protocol has two required methods(numberOfComponentsInPicerView:pickerView, pickerView:numberOfRowsInComponent).
  4. Connect the datasource just like actions and outlets.
  5. There's just one method for the delegate protocol(pickerView:titleForRow:forComponent).
  6. Add the IBOutlet and property to our view controller.
  7. Connect the picker to our outlet.
  8. Use our picker reference to pull the selected values(selectedRowInComponent).

@ vs. * : The "@" before those strings tells the compiler to make them NSString instead of char*. NSStrings are real Objective-C classes, as opposed to a simple C-style character pointer.



Added/Modified contents in .h file
@interface InstaTwitViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
{

    IBOutlet UIPickerView *tweetPicker
    NSArray* activities;
    NSArray* feelings;
}

@property (nonatomic, retain) UIPickerView* tweetPicker;
- (IBAction)sendButtonTapped: (id)sender;



Added/Modified contents in .m file
@implementation InstaTwitViewController
@synthesize tweetPicker;

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(component == 0)
    {

        return [activities count];
    }else{
        return [feelings count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger) component
{
    switch (component)
    {

        case 0:
            return [activities objectAtIndex:row];
        case 1:
            return [feelings objectAtIndex:row];
    }
    return nil;
}

- (IBAction)sendButtonTapped: (id)sender
{

    NSString* themessage = [NSString stringWithFormat:@"I'm %@ and feeling %@ about it.", [activities objectAtIndex:[tweetPicker selectedRowInComponent:0]], [feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]]];
    NSLog(themessage);
    //NSLog(@"Tweet button tapped!");

    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ID:PW@twitter.com/statuses/update.xml"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[[NSString stringWithFormat:@"status=%@", themessage] dataUsingEncoding:NSASCIIStringEncoding]];
    NSURLResponse* response;
    NSError* error;
    NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
    NSLog(@"%@", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);
}

- (void)viewDidLoad
{

    activities = [[NSArray alloc] initWithObjects:@"sleeping", @"eating", @"working", @"thinking", @"crying", @"begging", @"leaving", @"shopping", @"hello worlding", nil];
    feelings = [[NSArray alloc] initWithObjects:@"awesome", @"sad", @"happy", @"ambivalent", @"nauseous", @"psyched", @"confused", @"hopeful", @"anxious", nil];
    [super viewDidLoad];
}

- (void)dealloc
{

    [tweetPicker release];
    [activities release];
    [feelings release];
    [super dealloc];
}
  • achic 2010.09.14 21:51

    너무 잘봣어용
    근데 지금 이코드 입력하면 안되는데 혹시
    트위터사이트에서
    https://ID:PW@twitter.com/statuses/update.xml
    이것을 막아놨기 때문인가요?

    • Favicon of https://blog.missflash.com BlogIcon MissFlash 2010.09.15 10:12 신고

      ID와 PW 대신에 자신의 아이디 및 비밀번호를 넣으셔야 합니다.

      API가 바뀌지 않았다면 정상적으로 작동할 겁니다. ^_^;

  • 블루레전드 2011.09.13 20:11

    수고하십니다.
    생초보인데요. 저도 이 코드를 실행하니 콘솔에 에러가
    <error>Could not authenticate you.</error>
    <request>/statuses/update.xml</request>
    이렇게 뜨거든요. ID, PW는 모두 정확하게 입력했는데 말이죠.
    말씀대로 트위터의 API가 바뀐걸까요?

    • Favicon of https://blog.missflash.com BlogIcon MissFlash 2011.09.14 10:23 신고

      트위터 정책이 바뀌어서 아이디/패스워드를 직접 넣는 방식은 이제 지원하지 않을겁니다. 보안에 취약해서요...

      최근 문서를 참고하셔서 예제를 따라하셔야 할겁니다.