2011년 11월 2일 수요일

2011년 5월 30일 월요일

iphone http Request

1. Sync 



NSURL *url = [NSURL URLWithString:kURLPath]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
NSURLResponse *response; 
NSError *error = nil; 
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
if(data == nil) { NSLog(@”%@”, [error description]);
}


2. ASync 

NSURL *url = [NSURL URLWithString:kURLString]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
 [connection start];

NSUrlConnectionDelegate  사용




NSURLConnectionDelegate Header 응답
Body 전송
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse { response = [aResponse retain];
if ([response expectedContentLength] < 0) { [connection cancel];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData {
// 다운로드한 데이터를 추가 [receiveData appendData:aData];
}


NSURLConnectionDelegate
전송 완료
오류 처리
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
UIImage *image = [UIImage imageWithData:receiveData] [self.imageView setImage:image];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error"
[alert show]; [alert release];
}
message:[error description] delegate:self
cancelButtonTitle:@"Close" otherButtonTitles:nil];





ASIHTTPRequest
HTTP 요청과 응답 관련 라이브러리 간편한 사용성 보안 및 인증 지원 Queue를 활용한 다중 다운로드 지원
http://allseeing-i.com/ASIHTTPRequest/How-to-use


메모리 관리 기법 3가지

1.  retain  realse


2. pool 을 사용

main.m  을 사용..


NSAutoRealsePool pool = ... alloc 
  .... 
[pool drain] 
중첩해서 사용도 가능하다.. 



3. gabage collection

iphone map 이용하기

1. Map SDK 를 추가하고
2.   xlb   의   map view 에 delegate 를 추가한다.



//
//  SampleDay10ViewController.h
//  SampleDay10
//
//  Created by bit on 11. 5. 30..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import
#import

// delegate  를 추가한다. 
@interface SampleDay10ViewController : UIViewController {

MKMapView *mMap;
}

@property (nonatomic, retain) IBOutlet MKMapView *mMap;


-(IBAction)onViewModeChanged:(id)sender;
-(IBAction)onDropPinClicked:(id)sender;
-(IBAction)onCurrentPositionClicked:(id)sender;


@end



//
//  SampleDay10ViewController.m
//  SampleDay10
//
//  Created by bit on 11. 5. 30..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SampleDay10ViewController.h"

@implementation SampleDay10ViewController
@synthesize mMap;




/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];

mMap.showsUserLocation = YES;
mMap.delegate = self;
MKCoordinateRegion reg;
reg.center.latitude = 37.56;
reg.center.longitude = 126.96;
reg.span.latitudeDelta = 0.1;
reg.span.longitudeDelta = 0.1;
[mMap setRegion:reg animated:YES];
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


-(IBAction)onViewModeChanged:(id)sender{
NSUInteger idx = [(UISegmentedControl*)sender selectedSegmentIndex];
switch (idx) {
case 0:
mMap.mapType = MKMapTypeStandard;
break;
case 1:
mMap.mapType = MKMapTypeSatellite;
break;
case 2:
mMap.mapType = MKMapTypeHybrid;
break;

default:
break;
}
}
-(IBAction)onDropPinClicked:(id)sender{

MKReverseGeocoder *rev = [[MKReverseGeocoder alloc] initWithCoordinate:mMap.centerCoordinate];
rev.delegate = self;
[rev start];
}
-(IBAction)onCurrentPositionClicked:(id)sender{
MKCoordinateRegion reg = mMap.region;
MKUserLocation *userLocation = mMap.userLocation;
reg.center = userLocation.location.coordinate;
[mMap setRegion:reg animated:YES];
}


// google api 성공 일때 
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark 
{
NSLog(@"placemark = %@", placemark);
[mMap addAnnotation:placemark];
[geocoder release];
}


// google api  실패 일때 .. 주소가 없을때 .. 
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(@"%@", [error localizedDescription]);
[geocoder release];
}


-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
static NSString *viewIdentifier = @"My Annotate";
MKPinAnnotationView *pin = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:viewIdentifier];
if( pin == nil ){
pin = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:viewIdentifier] autorelease];
pin.animatesDrop = YES;
pin.pinColor = MKPinAnnotationColorPurple;
pin.canShowCallout = YES;
}
else {
pin.annotation = annotation;
}
return pin;
}


@end

2011년 5월 26일 목요일

iphone media 화일 재생

//
//  SampleDay9_2ViewController.h
//  SampleDay9-2
//
//  Created by bit on 11. 5. 26..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import
#import

@interface SampleDay9_2ViewController : UIViewController {

MPMoviePlayerController* player;
}

-(IBAction)onStart:(id)sender;
-(void)movieFinishCallback:(NSNotification*)aNotification;

@end


//
//  SampleDay9_2ViewController.m
//  SampleDay9-2
//
//  Created by bit on 11. 5. 26..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//



#import "SampleDay9_2ViewController.h"

// include 추가한다... 
// SDK     Media Framework 추가 한다
#import

@implementation SampleDay9_2ViewController



/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinishCallback:) name:MPMoviePlayerPlaybackDidFinishNotification object:player];

}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

-(void)movieFinishCallback:(NSNotification*)aNotification
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
}
-(IBAction)onStart:(id)sender
{
NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"movie" ofType:@"m4v"];
NSURL *url = [NSURL fileURLWithPath:moviePath];
// 서버에 리모트로 접근시 
// NSURL *url = [NSURL URLWithString:moviePath];
MPMoviePlayerViewController *mpView = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
//self.player = mpView.moviePlayer;
[self presentModalViewController:mpView animated:YES];
}
@end

iphone imagePicker 사용하여 이미지 버튼만들기

//
//  SampleDay9_1ViewController.h
//  SampleDay9-1
//
//  Created by bit on 11. 5. 26..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import

@interface SampleDay9_1ViewController : UIViewController {

IBOutlet UIButton *pictureButton;
}

@property (nonatomic, retain ) IBOutlet UIButton *pictureButton;

-(IBAction) onPhotoClicked:(id)sender ;

-(void)showImagePickerWithSourceType:(UIImagePickerControllerSourceType)sourceType ;
- (void) imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info;



@end




//
//  SampleDay9_1ViewController.m
//  SampleDay9-1
//
//  Created by bit on 11. 5. 26..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SampleDay9_1ViewController.h"

@implementation SampleDay9_1ViewController

@synthesize pictureButton;



/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
[pictureButton release];
[super dealloc];
}


-(IBAction) onPhotoClicked:(id)sender 
{
UIActionSheet *asheet;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {
asheet = [[UIActionSheet alloc] initWithTitle:@"Select Data Source" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album", @"Camera", nil ];
}
else {
asheet = [[UIActionSheet alloc] initWithTitle:@"Select Data Source" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album", nil ];
}
[asheet showInView:self.view];
[asheet release];
}


#pragma mark UICationSheet Delegate

-(void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if( buttonIndex == [actionSheet cancelButtonIndex]) return;
if(buttonIndex == 0 ) {
[self showImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
else if ( buttonIndex == 1 ) {
[self showImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera];
}
}


#pragma mark Image Picker Loading

-(void)showImagePickerWithSourceType:(UIImagePickerControllerSourceType)sourceType {
UIImagePickerController *picker = [[[UIImagePickerController alloc] init] autorelease ];
picker.sourceType = sourceType;
picker.allowsEditing = (sourceType == UIImagePickerControllerSourceTypeCamera );
picker.delegate = self;
[self presentModalViewController:picker animated:YES];
}

#pragma mark UIImagePickerController delegate

- (void) imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[pictureButton setImage:image forState:UIControlStateNormal];
[picker dismissModalViewControllerAnimated:YES];
}

- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissModalViewControllerAnimated:YES];
}

@end

iphone Quartz Animation

1.Quartz SDK  를 추가한다.




//
//  SampleDay9ViewController.m
//  SampleDay9
//
//  Created by bit on 11. 5. 26..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SampleDay9ViewController.h"

// 아래 소스를 넣어 주어야 한다..  자동완성 기능을 사용하기 위해서라도.. 

#import

@implementation SampleDay9ViewController



/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
UIButton *button = (UIButton *)[self.view viewWithTag:TAG_BUTTON];
[button addTarget:self action:@selector(animated:) forControlEvents:UIControlEventTouchUpInside];
}



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

-(IBAction)animated:(id)sender {
NSLog(@"Clicked Button!!!");
UIView *theView = [self.view viewWithTag:TAG_VIEW];
// transaction 기능은
// - 없어도 돌아 간다
// - randering 위해서... 
// - 추가 설정이 가능하다... 
// - 기본적인 설정을 받아서 사용할수 있다.. 
// Key-Value 코딩 설명 
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:2.0f] forKey:kCATransactionAnimationDuration];
CABasicAnimation *shrinkAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
shrinkAnimation.delegate = self;
shrinkAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
shrinkAnimation.toValue = [NSNumber numberWithFloat:0.0f];
[theView.layer addAnimation:shrinkAnimation forKey:@"shrinkAnimation"];
//회전
CABasicAnimation* spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
spinAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
spinAnimation.toValue = [NSNumber numberWithFloat:M_PI];
[theView.layer addAnimation:spinAnimation forKey:@"spinAnimation"];
// fade out 
CABasicAnimation* fadeAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
fadeAnimation.toValue = [NSNumber numberWithFloat:0.0f];
[theView.layer addAnimation:fadeAnimation forKey:@"fadeAnimation"];
[CATransaction commit];
}

@end