Школа-Студия разработки приложений для iOS. 3 лекция. Интерфейсы, прололжение
Школа-Студия разработки приложений для iOS. 5 лекция....
description
Transcript of Школа-Студия разработки приложений для iOS. 5 лекция....
Разное
Разработка приложений для iOS
Лекция 5
Глеб Тарасов
Возможности телефона
Интернет
Reachabilityhttp://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
Есть ли интернет?
Reachability *r = [Reachability reachabilityForInternetConnection];
if (r.status != NotReachable){ NSLog(@"Есть интернет");}
WiFi или 3G
Reachability *r = [Reachability reachabilityForLocalWiFi];if (r.status != NotReachable){ NSLog(@"Есть wifi");}
Акселерометр,гироскоп
Ориентация
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsPortrait(orientation)) NSLog(@"portrait");else NSLog(@"landscape");
typedef enum { UIInterfaceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight} UIInterfaceOrientation;
- (void)viewDidLoad{ [super viewDidLoad]; [[UIAccelerometer sharedAccelerometer] setDelegate:self]; [[UIAccelerometer sharedAccelerometer] setUpdateInterval:0.01];}
@interface MyViewController : UIViewController<UIAccelerometerDelegate>
#pragma mark - UIAccelerometerDelegate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{ NSLog(@"%g %g %g", acceleration.x, acceleration.y, acceleration.z);}
Акселерометр
Когда телефон лежит на столе:x = 0y = 0z = -1
ускорение +1.0g вдоль этой оси
1.0 по оси
Фильтр нижних частот
http://developer.apple.com/library/ios/#samplecode/AccelerometerGraph/Introduction/Intro.html
http://ru.wikipedia.org/wiki/Фильтр_нижних_частот
Гироскоп
- (void)viewDidLoad { [super viewDidLoad];) motionManager = [[CMMotionManager alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:1/30.0 target:self selector:@selector(doGyroUpdate) userInfo:nil repeats:YES];}
- (void)doGyroUpdate { CMRotationRate rate = motionManager.gyroData.rotationRate;) NSLog(@"%g %g %g", rate.x, rate.y, rate.z); }
радианы в секунду
Геолокация
manager = [[CLLocationManager alloc] init];manager.delegate = self;manager.desiredAccuracy = kCLLocationAccuracyHundredMeters;[manager startUpdatingLocation];
@interface Locator : NSObject<CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)m) didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLLocationCoordinate2D coord = newLocation.coordinate; NSLog(@"%g %g", coord.latitude, coord.longitude);}
Координаты
Центр Москвы: 55.747598, 37.626801
Компас
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading { NSLog(@"%g", newHeading.magneticHeading);}
locationManager = [[CLLocationManager alloc] init]; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager setDelegate:self]; [locationManager startUpdatingHeading];
0 - север, 90 - восток, 180 - юг, 270 - запад
Работа с микрофоном
http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html
SpeakHere
Воспроизведение аудио
AVAudioPlayer
NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"mp3"];NSURL *url = [NSURL fileURLWithPath:path];AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];[player play];
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent { if (receivedEvent.type == UIEventTypeRemoteControl) { switch (receivedEvent.subtype) { case UIEventSubtypeRemoteControlTogglePlayPause: [self playPause]; break; case UIEventSubtypeRemoteControlPreviousTrack: [self rewind]; break; case UIEventSubtypeRemoteControlNextTrack: [self forward]; break; default: break; } }}
- (void) viewDidAppear:(BOOL)animated{ [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder];}
Воспроизведение видео
NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"mp4"];NSURL *url = [NSURL fileURLWithPath:path];
MPMoviePlayerViewController *c = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentModalViewController:c animated:YES];
MPMoviePlayerViewController
Фото и видео
Фото/видео с камеры
UIImagePickerController *c = [[UIImagePickerController alloc] init];c.delegate = self;c.sourceType = UIImagePickerControllerSourceTypeCamera;c.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
[self presentModalViewController:c animated:YES];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
[picker dismissModalViewControllerAnimated:YES];}
Фото/видео из альбомов
UIImagePickerController *c = [[UIImagePickerController alloc] init];c.delegate = self;c.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL]; }
Поддержка iPad
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];} else { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];} else { self.viewController = [[ViewController_iPad alloc] initWithNibName:@"ViewController_iPad" bundle:nil];}
@implementation UIViewController (Utils)
+ (id)fromNib{ NSString *nibName = NSStringFromClass(self); return [self fromNib:nibName];}
+ (id)fromNib:(NSString *)nibName{ return [[self alloc] initWithNibName:nibName bundle:nil];}
@end
SplitViewController
Платное приложение Бесплатное приложение
Бесплатное демо + Платное приложение
Бесплатное приложение + InApp Purchases
настройка на itunesconnect.apple.com
настройка на itunesconnect.apple.com
+ поддержка в приложении
Платные приложения
InApp Purchases
MKStoreKit
https://github.com/MugunthKumar/MKStoreKit
StoreKithttp://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/Introduction/Introduction.html
[[MKStoreManager sharedManager] buyFeature:self.appleId onComplete:^(NSString *featureId, NSData *receiptData) { // ... купил } onCancelled:^{ // ... отказался }];
Демонстрация
Инструменты
XCode
Debugger
Instruments
Регистрация в Apple
индивидуальный аккаунт
регистрация
виртуальная карта
факс с оплатой
корпоративный аккаунт
факс с выпиской из ЕГРЮЛ
телефонный звонок по-английски
аккаунт
Несколько разработчиков на
портале
ФИО в графе «Разработчик» в
AppStore
~ 2-3 недели ~ 1 месяц
(Яндекс.Деньги, QIWI)
http://faxzero.com/
iTunes Connect (http://itunesconnect.apple.com)
Закрепим понимание
Несколько экранов - несколько UIViewController
Переходы между экранами:- UINavigationController- UITabBarController- presentModalViewController
Каждый экран (контроллер) рисуем в InterfaceBuilder
Если кода много - логику отрисовки выносим в отдельный наследник UIView
При запуске приложения создаем корневой контроллер и кладем его в window.rootViewController
Для изменения дизайна используем png-графику
Не забываем про @2x для retina-экранов
Большинство изменений интерфейса делаем с анимацией
Минимальный размер элемента, на который пользователь должен нажать: 44px
С сервером общаемся через XML или JSON
Работаем с сетью в фоновом потоке
Файлы локально сохраняем в Documents или Caches
Если нужно сохранить пару строк - используем NSUserDefaults
Если нужно сохранять много данных – CoreData
Загрузка больших файлов – ASIHTTPRequest
Перед выпуском в AppStore обязательно проверить работу на реальном устройстве
Тестируем желательно на самом старом поддерживаемом девайсе
Тестируем на всех поддерживаемых iOS
При выпуске новой версии не забыть проверить обновление
Ознакомиться с AppStore Review Guidelineshttps://developer.apple.com/appstore/guidelines.html
Книги
http://habrahabr.ru/post/118282/
Книги
iTunesUStanford University, Курс CS 193P
http://www.stanford.edu/class/cs193p
iTunesUWWDC videos
https://developer.apple.com/videos/wwdc/2011/
Совсем всё!
Глеб Тарасов[email protected]/pilot34