1 디바이스 정보 UIDevice 클래스가 제공하고 static 메서드인

Download Report

Transcript 1 디바이스 정보 UIDevice 클래스가 제공하고 static 메서드인

디바이스 정보
 UIDevice 클래스가 제공하고 static 메서드인 currentDevice가 객체를 생성합
니다.
 제공하는 정보
uniqueIdentifier: 장치 고유 ID / 회원가입을 하지 않고 어플을 운영 가능
model: 모델명
systemVersion:버전
orientation: 현재 기계의 방향
batteryLevel: 배터리 양
batteryState: 상태(충전중인지 아닌지)
proximityState: 물체와의 상태 - 근접센서에 관련
1
예제
2
1. View-Based Application 프로젝트 생성(ResourceTest)
2. ResourceTestViewController. h 파일에 2개의 프로토콜을 적용하고 UITableView 변수를 생성
#import <UIKit/UIKit.h>
@interface ResourceTestViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
{
UITableView * table;
}
@end
3
3. ResourceTestViewController. m 파일에 viewDidLoad 메서드 재정의
- (void)viewDidLoad
{
[super viewDidLoad];
table = [[UITableView alloc]initWithFrame:CGRectMake(0,0,320,480) style:UITableViewStyleGrouped];
table.delegate = self;
table.dataSource = self;
[self.view addSubview:table]; //배열에 add가 생기면 retain이 발생한다.
[table release];
}
4. ResourceTestViewController. m 파일에 테이블 뷰 출력 메서드 구현
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView //섹션의 갯수
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section //행의 수
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
}
cell.textLabel.text = @"장치 정보 보기";
return cell;
}
4
5
5. 장치 정보를 출력할 UITableViewController로 부터 상속받는 클래스 생성(DeviceInfo)
6. ResourceTestViewController.m 파일에 DeviceInfo.h 파일 import
7. ResourceTestViewController.m 파일에 셀을 호출했을 때 호출되는 메서드 작성
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DeviceInfo * sub = [[DeviceInfo alloc]initWithStyle:UITableViewStyleGrouped];
UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:sub];
navi.view.frame = CGRectMake(0,-20,320,480); //초기 위치
[self.view addSubview:navi.view];
}
8. ResourceTestViewController.m 파일의 dealloc 메서드에 추가
- (void)dealloc
{
[table release];
[super dealloc];
}
6
7
9. DeviceInfo.m 파일에 viewDidLoad 메서드 재정의
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:@"뒤로"
style:UIBarButtonItemStyleDone target:self action:@selector(goBack)]autorelease];
self.title = @"장치 정보";
}
10. DeviceInfo.m 파일에 goBack 메서드 구현
-(void)goBack
{
[self.navigationController.view removeFromSuperview];
}
8
11. DeviceInfo.m 파일에 테이블 뷰 출력 메서드 수정 및 구현
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView //섹션 갯수
{
return 6;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section //행의 갯수(x6)
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
}
UIDevice *device = [UIDevice currentDevice];
switch (indexPath.section)
{
case 0://UDID출력
cell.textLabel.text = [device uniqueIdentifier];
break;
case 1: //이름출력
cell.textLabel.text = [device name];
break;
9
case 2:
cell.textLabel.text = [device systemVersion];
break;
case 3:
cell.textLabel.text = [device model];;
break;
case 4://시뮬레이터에서는 확인할 수 없음
if (device.batteryState == UIDeviceBatteryStateUnplugged)
cell.textLabel.text = @"충전 중이 아님";
else if (device.batteryState == UIDeviceBatteryStateCharging)
cell.textLabel.text = @"충전 중";
else if (device.batteryState == UIDeviceBatteryStateFull)
cell.textLabel.text = @"충전 완료";
break;
case 5:
switch (device.orientation)
{
case UIDeviceOrientationPortrait:
cell.textLabel.text = @"홈 버튼 아래";
break;
case UIDeviceOrientationPortraitUpsideDown:
cell.textLabel.text = @"홈 버튼 위";
break;
case UIDeviceOrientationLandscapeLeft:
cell.textLabel.text = @"홈 버튼 왼쪽";
break;
case UIDeviceOrientationLandscapeRight:
cell.textLabel.text = @"홈 버튼 아래";
break;
}
break;
}
return cell;
}
10
12. DeviceInfo.m 파일에 섹션의 타이틀을 만드는 메서드 구현
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString * str;
switch (section)
{
case 0://필수
str = @"UDID";
break;
case 1:
str = @"장치이름";
break;
case 2: //필수
str = @"IOS 버전";
break;
case 3://필수-하드웨어적인 스펙 구별할때 사용
str = @"장치모델";
break;
case 4:
str = @"충전상태";
break;
case 5://필수
str = @"장치방향";
break;
}
return str;
}
11
12
OpenURL 사용
사파리를 이용한 웹 사이트의 접속은 [[UIApplication sharedApplication]
openURL:(NSURL *)url]을 이용하면 됩니다.
이 경우 사파리를 직접 구동시켜 수행을 해 줍니다.
전화걸기: [[UIApplication sharedApplication] openURL: [NSURL
URLWithString:@"tel:전화번호"]];
문자 보내기: [[UIApplication sharedApplication] openURL: [NSURL
URLWithString:@"sms:전화번호"]];
지도보기: [[UIApplication sharedApplication] openURL: [NSURL
URLWithString:@"http://maps.google.com/maps?q=지역명"]];
아이튠스 접속하기:[[UIApplication sharedApplication] openURL: [NSURL
URLWithString:@”http://itunes.apple.com/kr/app/id숫자?mt=8”]]
13
예제
14
1. 이전 프로젝트의 ResourceTestViewController.m 파일의 테이블 뷰 출력 메서드 수정
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
}
if(indexPath.section == 0)
cell.textLabel.text = @"장치 정보 보기";
else if(indexPath.section == 1)
cell.textLabel.text = @"전화 걸기";
else if(indexPath.section == 2)
cell.textLabel.text = @"문자 보내기";
else if(indexPath.section == 3)
cell.textLabel.text = @"서울 지역 지도 보기";
else if(indexPath.section == 4)
cell.textLabel.text = @"카카오 톡 보기";
return cell;
15
}
16
2. ResourceTestViewController.m 파일의 셀을 선택했을 때 호출되는 메서드 수정
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section == 0)
{
DeviceInfo * sub = [[DeviceInfo alloc]initWithStyle:UITableViewStyleGrouped];
UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:sub];
navi.view.frame = CGRectMake(0,-20,320,480);
[self.view addSubview:navi.view];
}
else if(indexPath.section == 1)
{
NSString *str = [NSString stringWithString:@"tel:010-8602-1996"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
else if(indexPath.section == 2)
{
NSString *str = [NSString stringWithString:@"sms:010-3790-1997"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
else if(indexPath.section == 3)
{
NSString *str = [NSString stringWithString:@"http://maps.google.com/maps?q=Seoul"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}
else if(indexPath.section == 4)
{
NSString *str = [NSString stringWithString:@"http://itunes.apple.com/kr/app/id362057947?mt=8"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
17
}
}
18
Email 보내기
메일보내기 창을 이용해서 보낼 수 있으며 URL을 이용해서 직접 전송할 수 있습니다.
MessageUI.framework 프레임워크를 이용합니다.
클래스는 <MessageUI/MFMailComposeViewController.h>를 import해야 합니다.
<MFMailComposeViewControllerDelegate>를 따르면 메일 전송 후 결과를 알 수 있습
니다.
 MFMailComposeViewController 클래스의 객체를 메모리 할당과 초기화를 수행하고 이
객체의 mailComposeDelegate 속성에 메일을 보내고 난 후 처리할 메서드를 소유하고
있는 객체를 지정합니다.
 객체를 화면에 출력하면 됩니다.
 결과를 확인하는 메서드 – result 값이 메일보내기 결과입니다.




-(void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
result 값 : MFMailComposeResultCancelled//메일을 보내려고했는데 전화가 왔을때가 cancelled임,
MFMailComposeResultSaved,
MFMailComposeResultSent, MFMailComposeResultFailed//메일발송 실패
19
 멤버 메서드
+ (BOOL)canSendMail => 메일의 전송 여부
- (void)addAttachmentData:(NSData*)attachment
mimeType:(NSString*)mimeType fileName:(NSString*)filename
ex) 이미지 파일의 경우
NSData * data = [NSData dataWithContentsOfFile:파일경로];
[객체 addAttachmentData:data mimeType:@"image/png" fileName:@"파일명"];
- (void)setToRecipients:(NSArray*)toRecipients
- (void)setBccRecipients:(NSArray*)bccRecipients
- (void)setCcRecipients:(NSArray*)ccRecipients
- (void)setMessageBody:(NSString*)body isHTML:(BOOL)isHTML
- (void)setSubject:(NSString*)subjec
20
예제
21
1. 이전 프로젝트의 ResourceTestViewController.m 파일의 테이블 뷰 출력 메서드 수정
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]
autorelease];
}
if(indexPath.section == 0)
cell.textLabel.text = @"장치 정보 보기";
else if(indexPath.section == 1)
cell.textLabel.text = @"전화 걸기";
else if(indexPath.section == 2)
cell.textLabel.text = @"문자 보내기";
else if(indexPath.section == 3)
cell.textLabel.text = @"서울 지역 지도 보기";
else if(indexPath.section == 4)
cell.textLabel.text = @"카카오 톡 보기";
else if(indexPath.section == 5)
cell.textLabel.text = @"이메일 보내기";
return cell;
}
22
23
2. ResourceTestViewController.m 파일의 테이블 뷰에서 셀을 선택했을 때 호출되는 메서드에 추가
else if(indexPath.section == 5)
{
MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
mail.mailComposeDelegate = self;
[mail setToRecipients:[NSArray arrayWithObject:@"[email protected]"]];
[self presentModalViewController:mail animated:YES];
[mail release]; //modal은 반드시 바로 릴리즈
}
24
3. ResourceTestViewController.m 파일에 delegate 메서드 구현
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
NSString * str;
if(result == MFMailComposeResultSent)
{
str = @"메일 보내기 성공";
}
else if(result == MFMailComposeResultSaved)
{
str = @"임시 저장";
}
else if(result == MFMailComposeResultFailed)
{
str = @"실패";
}
UIAlertView * dlg = [[UIAlertView alloc] initWithTitle:@"메일보내기" message:str delegate:nil
cancelButtonTitle:@"확인"otherButtonTitles:nil];
[dlg show];
[dlg release];
[controller dismissModalViewControllerAnimated:YES]; //메일을 보낸 후 모달이 dismiss되도록.
}
25
26
4. 프로젝트에 MessageUI.framework 링크 추가
5. ResourceTestViewController.h 파일에 import 하고 delegate 추가
#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
@interface ResourceTestViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource,MFMailComposeViewControllerDelegate>
{
UITableView * table;
}
@end
27
가속도 센서 사용
 Iphone에서부터는 가속도 센서를 사용할 수 있습니다.
 UIAccelerometer 클래스가 관리하며 sharedAccelerometer 메서드로 객체를
생성합니다.
 객체의 x,y,z 프로퍼티를 이용하면 가속된 방향을 알 수 있습니다.
 delegate가 구현되어 있으며 - (void)accelerometer:(UIAccelerometer
*)accelerometer didAccelerate:(UIAcceleration *)acceleration 메서드를 이용
해서 감지할 수 있습니다.
 delegate가 nil이 되면 가속도계를 더이상 사용하지 않는다는 의미입니다.
 UpdateInterval 속성을 이용하여 얼마나 자주 데이터를 받을 것인지를 설정합
니다.
28
1. 이전 프로젝트에 이어서 작성
2. UIViewController로 부터 상속받는 클래스 생성(Accel)
3. ResourceTestViewController. h 파일에 헤더파일을 import하고 변수 선언
#import <UIKit/UIKit.h>
#import <MessageUI/MFMailComposeViewController.h>
#import "Accel.h"
@interface ResourceTestViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource,MFMailComposeViewControllerDelegate>
{
UITableView * table;
Accel *
accelView;
}
@end
29
4. ResourceTestViewController. m 파일의 테이블 뷰에 섹션 만들어주는 메서드 수정
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 7;
}
5. ResourceTestViewController. m 파일의 테이블 뷰에 셀을 그려주는 메서드에 추가
else if(indexPath.section == 6)
cell.textLabel.text = @"가속도 센서";
6. ResourceTestViewController. m 파일의 테이블 뷰의 셀을 선택할 때 호출되는 메서드에 추가
else if(indexPath.section == 6)
{
accelView = [[[Accel alloc]init]autorelease];
UINavigationController * navi = [[[UINavigationController
alloc]initWithRootViewController:accelView]autorelease];
accelView.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:@"뒤로"
style:UIBarButtonItemStyleDone
target:self action:@selector(accelClick)]autorelease];
[self presentModalViewController:navi animated:YES];
}
7. ResourceTestViewController. m 파일에 메서드 추가
-(void)accelClick
{
[accelView dismissModalViewControllerAnimated:YES];
}
30
8. Accel.h 파일에 변수 선언
#import <UIKit/UIKit.h>
@interface Accel : UIViewController <UIAccelerometerDelegate>
{
IBOutlet UILabel *labelX;
IBOutlet UILabel *labelY;
IBOutlet UILabel *labelZ;
IBOutlet UIProgressView* progressX;
IBOutlet UIProgressView* progressY;
IBOutlet UIProgressView* progressZ;
float accel[3];
IBOutlet UIImageView* imgView;
}
@end
31
9. Accel.m 파일에 viewDidLoad 메서드 재정의
- (void)viewDidLoad
{
[super viewDidLoad];
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 60)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"target.png"]];
[self.view addSubview:imgView];
}
32
10. Accel.m 파일에 delegate 메서드 구현
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
accel[0] = (acceleration.x * 0.1) + (accel[0] * (1.0 - 0.1));
accel[1] = (acceleration.y * 0.1) + (accel[1] * (1.0 - 0.1));
accel[2] = (acceleration.z * 0.1) + (accel[2] * (1.0 - 0.1));
labelX.text = [NSString stringWithFormat:@"%f",accel[0]];
labelY.text = [NSString stringWithFormat:@"%f",accel[1]];
labelZ.text = [NSString stringWithFormat:@"%f",accel[2]];
progressX.progress = (accel[0]+1.0)/2;
progressY.progress = (accel[1]+1.0)/2;
progressZ.progress = (accel[2]+1.0)/2;
CGRect newFrame;
newFrame.size.width = imgView.image.size.width * (0.5 + (accel[2]+1.0)/2);
newFrame.size.height = imgView.image.size.height * (0.5 + (accel[2]+1.0)/2);
newFrame.origin.x = (self.view.frame.size.width * (1.0 - (accel[0]+1.0)/2)) - (newFrame.size.width/2);
newFrame.origin.y = (self.view.frame.size.height * (accel[1]+1.0)/2) - (newFrame.size.height/2);
imgView.frame = newFrame;
}
33
34
11. Accel.m 파일의 dealloc에 추가
- (void)dealloc
{
[[UIAccelerometer sharedAccelerometer] setDelegate:nil];
[labelX release];
[labelY release];
[labelZ release];
[progressX release];
[progressY release];
[progressZ release];
[imgView release];
[super dealloc];
}
35
12. Accel.xib 파일의 view에 레이블을 3개 배치하고 프로그래스 뷰를 3개 배치하고 연결
13. target.png 파일을 리소스 폴더에 복사
36
코어 로케이션 이용
 IPhone에서 위치 정보를 제공하는 클래스는 CoreLocation 프레임워크에 있는
CLLocationManager 클래스가 담당합니다.
 CLLocationManagerDelegate 프로토콜에 있는 메서드를 이용해서 위치 정보를
받아오게 됩니다.
 locationManager:didFailWithError:은 에러 발생 시 호출되는 메서드입니다.
 locationManager:didUpdateToLocation:fromLocation은 위치 정보가 업데이트
될 때 호출되는 메서드 입니다.
 CLLocationManager클래스는 멤버로CLLocationCoordinate2D 타입의
coordinate구조체를 가지고 있는데 coordinate.latitude이면 위도를
CLLocationDegrees 타입으로 리턴하며 경도는 coordinate.longitude를 호출하
면 CLLocationDegrees 타입으로 리턴합니다.
 altitude 속성을 호출하면 고도를 리턴해 줍니다.
 timestamp는 위치를 구한 시간을 넘겨 줍니다.
 getDistanceFrom은 CLLocationManager 객체 사이의 거리를 리턴합니다.
37
startUpdatingLocation: 위치 정보를 받기 시작
stopUpdatingLocation: 위치 정보 수집을 중단
distanceFilter: 지정한 거리 이상을 이동해야 로케이션 정보 업데이트(미터 단위)
desiredAccuracy: 위치 정보의 정확도
38
예제
1. ViewBased Application프로젝트를 생성(Location)
2. Location.h 파일에 변수 선언
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface Location : UIViewController<CLLocationManagerDelegate> {
CLLocationManager *locationManager;
UILabel * label1;
UILabel * label2;
UILabel * label3;
}
@property (retain, nonatomic) IBOutlet UILabel *label1;
@property (retain, nonatomic) IBOutlet UILabel *label2;
@property (retain, nonatomic) IBOutlet UILabel *label3;
@property (retain, nonatomic) CLLocationManager *locationManager;
@end
39
3. Location.m 파일에 synthesize 지정
@synthesize
@synthesize
@synthesize
@synthesize
label1;
label2;
label3;
locationManager;
4. Location.m 파일의 viewDidLoad 재정의
- (void)viewDidLoad
{
self.locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
5. Location.m 파일의 dealloc 재정의
- (void)dealloc {
[locationManager release];
[label1 release];
[label2 release];
[label3 release];
[super dealloc];
}
40
6. Location.m 파일에 delegate 메서드 재정의
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
label1.text = [[NSString alloc] initWithFormat:@"%g°", newLocation.coordinate.latitude];
label2.text = [[NSString alloc] initWithFormat:@"%g°", newLocation.coordinate.longitude];
label3.text = [[NSString alloc] initWithFormat:@"%gm",newLocation.altitude];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView *dlg = [[UIAlertView alloc]
initWithTitle:@"에러"
message:@"위치 정보 가져오기 실패"
delegate:nil
cancelButtonTitle:@"확인"
otherButtonTitles:nil];
[dlg show];
[dlg release];
}
7. Location.xib 파일에 레이블을 3개 배치하고 IBOutlet변수와 연결
8. 프로젝트에 CoreLocation.framework 링크 추가
41
MapView
맵뷰는 구글 맵을 이용해서 화면에 위치 정보를 출력해주는 클래스입니다.
이 클래스는 MapKit 프레임워크에 있습니다.
MKMapView는 맵 뷰 클래스로 사용자에게 지도를 보여주는 역할을 하는 클래
스입니다.
MapType 프로퍼티를 이용하면 보기 모드를 설정할 수 있습니다.
(MKMapTypeStandard, MKMapTypeSatellite, MKMapTypeHybrid)
사용자의 위치 정보 사용은 showsUserLocation 프로퍼티를 YES로 설정하면 사
용이 가능합니다.
userLocation 프로퍼티에 접근하면 MKUserLocation 인스턴스를 반환합니다.
MKUserPosition은 현재 사용자 위치 정보를 위한 객체로 맵뷰에서 가져옵니다.
위의 객체는 CLLocation 객체인 location 프로퍼티를 갖습니다.
다시 CLLocation은 좌표를 나타내는 coordinate라는 프로퍼티를 가지고 있습니
42
다.
맵 뷰의 위치 설정

MKCoordinateRegion는 위치 정보를 보여주기 위한 구조체입니다.

이 구조체는 2가지 멤버를 소유하고 있는데 하나는 center입니다.

CLLocationCoordinate2D 타입의 구조체로 latitude와 longitude 값을 가지고
지구 상의 한 지점을 화면의 중앙에 표시합니다.

다른 하나의 멤버는 span으로 MKCoordinateSpan구조체로 구성되어 있는
데 latitudeDelta 와 longitudeDelta를 이용해서 표시할 영역의 확대 수준을
정합니다.
맵 뷰의 위치 정보

MKReverseGeocoder는 위치 정보를 해석해서 알려주는 클래스입니다.

주소를 알고 싶은 지역의 좌표를 넘겨주고 delegate를 설정하면 됩니다.

이 메서드는 위치 정보를 해석하는데 실패하면
(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError
*)error 메서드를 호출하고 성공하면
(void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFindPlacemark:(MKPlacemark *)placemark를 호출합니다.
43
예제
1. View-Based Application 프로젝트 생성(Map)
2. MapKit 프레임워크 추가
3. MapViewController.h 파일에 변수 선언 및 메서드 선언
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController {
IBOutlet MKMapView* mapView;
}
-(IBAction)Mode:(id)sender;
-(IBAction)Position:(id)sender;
-(IBAction)Pin:(id)sender;
@end
44
4. MapViewController.m 파일에 메서드 구현
- (void)viewDidLoad
{
[super viewDidLoad];
mapView.showsUserLocation = YES;
MKCoordinateRegion reg;
reg.center.latitude = 37.5568;
reg.center.longitude = 126.945777;
reg.span.latitudeDelta = 0.01;
reg.span.longitudeDelta = 0.01;
[mapView setRegion:reg animated:YES];
}
45
-(IBAction) Mode:(id)sender
{
int idx = [sender selectedSegmentIndex];
if (idx==0)
mapView.mapType = MKMapTypeStandard;
else if (idx==1)
mapView.mapType = MKMapTypeSatellite;
else
mapView.mapType = MKMapTypeHybrid;
}
46
-(IBAction)Position:(id)sender
{
MKCoordinateRegion region;
region.center.latitude = 37.495835;
region.center.longitude = 127.029097;
//region.center.latitude = mapView.userLocation.coordinate.latitude;
//region.center.longitude = mapView.userLocation.coordinate.longitude;
region.span.latitudeDelta = 0.01;
region.span.longitudeDelta = 0.01;
[mapView setRegion:region animated:YES];
}
47
-(IBAction)Pin:(id)sender
{
NSLog(@"Query : lat: %f, long:
%f",mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude);
MKReverseGeocoder *rev = [[MKReverseGeocoder alloc]
initWithCoordinate:mapView.centerCoordinate];
rev.delegate = self;
[rev start];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder
didFindPlacemark:(MKPlacemark *)placemark {
[mapView addAnnotation:placemark];
[geocoder release];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError
*)error {
NSLog(@"%@", [error localizedDescription]);
[geocoder release];
}
5. dealloc에 추가 - [mapView release];
48
6. 화면에 맵뷰 1개와 세그먼트1개(3개 짜리)와 버튼2개를 배치하고 변수와 이벤트 연결
주소록 API
주소록 API를 이용하는 방법은 2가지 입니다.
C기반의 코어 서비스 계층에 있는 AddressBook 프레임워크를 이용할 수 있고
UserInterface가 이미 구현되어 있는 AddressBookUI 프레임워크를 이용하는 방
법이 있습니다.
AddressBook 프레임워크를 이용하는 경우는 C기반으로 데이터가 리턴되며 메
서드도 CF가 붙는 경우가 많습니다.
AddressBookUI 프레임워크를 이용하는 경우는 4개의 뷰 컨트롤러를 이용할 수
있습니다.
ABNewPersonViewController: 새로운 연락처 추가
ABPeoplePickerNavigationController: 연락처를 검색하고 선택
ABPersonViewController: 연락처 정보 보기 및 편집
ABUnknownPersonViewController: 일부 정보를 이용해서 새로운 연락처에 추가
하거나 병합할 때 사용하는 클래스
49
예제
1. View-Based Application 프로젝트 생성(Map)
2. MapKit 프레임워크 추가
3. MapViewController.h 파일에 변수 선언 및 메서드 선언
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface MapViewController : UIViewController {
IBOutlet MKMapView* mapView;
}
-(IBAction)Mode:(id)sender;
-(IBAction)Position:(id)sender;
-(IBAction)Pin:(id)sender;
@end
50