NSInteger signedInteger = -123; /* Может принимать отрицательные числа. */
NSUInteger unsignedInteger = 123; /* Не может принимать отрицательные числа. */
float /* Может хранить числа с точкой, такие как 1.23 или 73.12 */
NSString /* Может хранить строки, такие как: "Mrs Thomson." */
NSArray /* Может хранить только массивы содержащие объекты! */
NSSet /* Может хранить только уникальные значения переменных. NSSet похожи на массивы, так как могут хранить внутри себя несколько значений сразу, но каждое значение должно быть внутри набора уникальным.*/
Условия выбора IF-ELSE
if ("какое-то условие"){
/* Этот код выполниться если условие даст TRUE. */
} else {
/* Этот код выполниться если условие даст FALSE. */
}
NSObject *object1 = [[NSObject alloc] init];
NSObject *object2 = object1;
if ([object1 isEqual:object2]) {
NSLog(@"Объекты идентичны.");
} else {
NSLog(@"Объекты различны.");
}
Циклы FOR
for ("код, который должен выполниться перед началом цикла";
"условие, при котором будет завершен весь цикл";
"код, который выполнится во время итерации цикла") {
}
char *myString = "This is my string";
NSUInteger counter = 0;
for (counter = 0;
counter < strlen(myString);
counter++) {
char character = myString[counter];
NSLog(@"%c", character);
}
char *myString = "This is my string";
NSUInteger counter = 0;
for (; /* Пустое начальное условие */
counter < strlen(myString);
counter++) {
char character = myString[counter];
NSLog(@"%c", character);
}
Циклы WHILE
while ("какое-то условие") {
"Ваш код"
}
NSUInteger counter = 0;
while (counter < 10) {
NSLog(@"Counter = %lu", (unsigned long)counter);
counter++;
}
while (YES) {
/* Бесконечный цикл. */
}
Простой класс Class
Файл Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
@end
Файл Person.m
#import "Person.h"
@implementation Person
- (id)init
{
self = [super init];
if (self) {
// Ваш код инициализации объекта.
}
return self;
}
@end
Простая функция Function
void sendEmailTo(const char *paramTo,
const char *paramSubject,
const char *paramEmailMessage) {
/* Код тела функции. */
}
sendEmailTo("somebody@somewhere.com",
"My Subject",
"Please read my email");
BOOL sendEmailTo(const char *paramTo,
const char *paramSubject,
const char *paramEmailMessage) {
/* Код тела функции. */
if (paramTo == nil ||
paramSubject == nil ||
paramEmailMessage == nil){
NSLog(@"Переданы пустые параметры Nil.");
return NO;
} else {
return YES;
}
}
BOOL isSuccessful = sendEmailTo("somebody@somewhere.com",
"My Subject",
"Please read my email");
if (isSuccessful){
/* Письмо послано. */
} else {
/* Произошла ошибка. Письмо не послано. */
}
Простой метод Method
- (BOOL) sendEmailTo: (NSString *) paramTo
withSubject: (NSString *) paramSubject
andEmailMessage: (NSString *) paramEmailMessage {
if ([paramTo length] == 0 ||
[paramSubject length] == 0 ||
[paramEmailMessage length] == 0) {
NSLog(@"Переданы пустые параметры Nil.");
return NO;
} else {
return YES;
}
}
[self sendEmailTo: @"someone@somewhere.com"
withSubject: @"My Subject"
andEmailMessage:@"Please read my email."];
Создание объекта
MyObject *someObject = [[MyObject alloc] init];
[someObject doSomething];
Синтезирование установщиков и получателей значений переменных внутри класса
Файл Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString *firstName;
}
@property (nonatomic, strong) NSString *firstName;
@end
Файл Person.m
#import "Person.h"
@implementation Person
@synthesize firstName;
- (id)init {
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
@end
Файл main.m
Person *myPerson= [[Person alloc] init];
myPerson.firstName = @"Boris";
NSLog(@"%@", myPerson.firstName);
/* ИЛИ */
[myPerson firstName: @"Boris"];
NSLog(@"%@", [myPerson firstName]);
Загрузка данных из файла проекта BUNDLE
- (BOOL) application: (UIApplication *)application
didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
NSString *FilePath = [[NSBundle mainBundle] pathForResource: @"AlanSugar" ofType:@"png"];
if ([FilePath length] > 0) {
UIImage *image = [UIImage imageWithContentsOfFile: FilePath];
if (image != nil) {
NSLog(@"Successfully loaded the file as an image.");
} else {
NSLog(@"Failed to load the file as an image.");
}
} else {
NSLog(@"Could not find this file in the main bundle.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Загрузка нескольких файлов из проекта BUNDLE
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
if ([resourcesBundlePath length] > 0) {
NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath];
if (resourcesBundle != nil){
NSArray *PNGPaths = [resourcesBundle pathsForResourcesOfType:@"png"
inDirectory:@"images"];
[PNGPaths enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Path %lu = %@", (unsigned long)idx+1, obj);
}];
} else {
NSLog(@"Failed to load the bundle.");
}
} else {
NSLog(@"Could not find the bundle.");
}
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Передача сообщения в NOTIFICATION CENTER
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
/* Имя notification */
const NSString *ResultOfAppendingTwoStringsNotification =
@"ResultOfAppendingTwoStringsNotification";
/* Ключи внутри хэщ-массива, который пересылает наше сообщение notification. */
const NSString
*ResultOfAppendingTwoStringsFirstStringInfoKey = @"firstString";
const NSString
*ResultOfAppendingTwoStringsSecondStringInfoKey = @"secondString";
const NSString
*ResultOfAppendingTwoStringsResultStringInfoKey = @"resultString";
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSString *firstName = @"Anthony";
NSString *lastName = @"Robbins";
NSString *fullName = [firstName stringByAppendingString:lastName];
NSArray *objects = [[NSArray alloc] initWithObjects:
firstName,
lastName,
fullName,
nil];
NSArray *keys = [[NSArray alloc] initWithObjects:
ResultOfAppendingTwoStringsFirstStringInfoKey,
ResultOfAppendingTwoStringsSecondStringInfoKey,
ResultOfAppendingTwoStringsResultStringInfoKey,
nil];
NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:objects
forKeys:keys];
NSNotification *notificationObject = [NSNotification notificationWithName:(NSString *) ResultOfAppendingTwoStringsNotification object:self userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notificationObject];
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Отслеживание прихода сообщений NOTIFICATION CENTER
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
/* Имя notification */
const NSString *ResultOfAppendingTwoStringsNotification =
@"ResultOfAppendingTwoStringsNotification";
/* Ключи внутри хэщ-массива, который пересылает наше сообщение notification. */
const NSString
*ResultOfAppendingTwoStringsFirstStringInfoKey = @"firstString";
const NSString
*ResultOfAppendingTwoStringsSecondStringInfoKey = @"secondString";
const NSString
*ResultOfAppendingTwoStringsResultStringInfoKey = @"resultString";
- (void) broadcastNotification{
NSString *firstName = @"Anthony";
NSString *lastName = @"Robbins";
NSString *fullName = [firstName stringByAppendingString:lastName];
NSArray *objects = [[NSArray alloc] initWithObjects:
firstName,
lastName,
fullName,
nil];
NSArray *keys = [[NSArray alloc] initWithObjects:
ResultOfAppendingTwoStringsFirstStringInfoKey,
ResultOfAppendingTwoStringsSecondStringInfoKey,
ResultOfAppendingTwoStringsResultStringInfoKey,
nil];
NSDictionary *userInfo = [[NSDictionary alloc] initWithObjects:objects
forKeys:keys];
NSNotification *notificationObject =[NSNotification notificationWithName:(NSString *)ResultOfAppendingTwoStringsNotification object:self userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notificationObject];
}
- (void) appendingIsFinished:(NSNotification *)paramNotification{
NSLog(@"Notification is received.");
NSLog(@"Notification Object = %@", [paramNotification object]);
NSLog(@"Notification User-Info Dict = %@", [paramNotification userInfo]);
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
/* Отслеживание сообщения notification */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appendingIsFinished:) name:(NSString *)ResultOfAppendingTwoStringsNotification object:self];
[self broadcastNotification];
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application{
/* Далее мы больше не отслеживаем никаких сообщений notifications. */
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Alert через UIAlertView
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok", nil];
[alertView show];
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:[self yesButtonTitle]]){
NSLog(@"User pressed the OK button.");
} else if ([buttonTitle isEqualToString:[self noButtonTitle]]){
NSLog(@"User pressed the Cancel button.");
}
}
/* Отображение поля ввода в Alert. */
UITextField *textField = [alertView textFieldAtIndex:0];
textField.keyboardType = UIKeyboardTypeNumberPad;
[alertView show];
/* Отображение поля ввода пароля в Alert. */
[alertView setAlertViewStyle:UIAlertViewStyleSecureTextInput];
[alertView show];
/* Отображение поля ввода логина пароля в Alert. */
[alertView setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[alertView show];
Переключатели SWITCH через UISwitch
Файл Creating_and_Using_Switches_with_UISwitchViewController.h
#import <UIKit/UIKit.h>
@interface Creating_and_Using_Switches_with_UISwitchViewController
: UIViewController
@property (nonatomic, strong) UISwitch *mySwitch;
@end
Файл Creating_and_Using_Switches_with_UISwitchViewController.m
#import "Creating_and_Using_Switches_with_UISwitchViewController.h"
@implementation Creating_and_Using_Switches_with_UISwitchViewController
@synthesize mySwitch;
- (void)viewDidLoad {
[super viewDidLoad];
/* Делаем фон View белым. */
self.view.backgroundColor = [UIColor whiteColor];
/* Создаем switch. */
self.mySwitch = [[UISwitch alloc] initWithFrame: CGRectMake(100, 100, 0, 0)];
/* Создаем switch на View. */
[self.view addSubview: self.mySwitch];
/* Устанавливаем Switch на On. */
[self.mySwitch setOn:YES];
/* Отслеживание переключения Switch. */
[self.mySwitch addTarget:self
action:@selector(switchIsChanged:)
forControlEvents:UIControlEventValueChanged];
}
/* Метод, вызываемый при переключении Switch. */
- (void) switchIsChanged:(UISwitch *)paramSender{
NSLog(@"Sender is = %@", paramSender);
if ([paramSender isOn]){
NSLog(@"The switch is turned on.");
} else {
NSLog(@"The switch is turned off.");
}
}
Крутящиеся барабаны выбора UIPickerView
Файл Picking_Values_with_UIPickerViewViewController.h
@interface Picking_Values_with_UIPickerViewViewController
: UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) UIPickerView *myPicker;
@end
Фйал Picking_Values_with_UIPickerViewViewController.m
#import "Picking_Values_with_UIPickerViewViewController.h"
@implementation Picking_Values_with_UIPickerViewViewController
@synthesize myPicker;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/* Создание Барабана выбора */
self.myPicker = [[UIPickerView alloc] init];
/* Установка делегата классу Picking_Values_with_UIPickerViewViewController */
self.myPicker.delegate = self;
/* Установка источника данных из массива */
self.myPicker.dataSource = someArray;
/* Установка полосы селектора */
self.myPicker.showsSelectionIndicator = YES;
/* Центрирование Барабана выбора */
self.myPicker.center = self.view.center;
/* Добавление Барабана выбора на экран */
[self.view addSubview:self.myPicker];
}
/* Установка числа барабанов */
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
NSInteger result = 0;
if ([pickerView isEqual: self.myPicker]){
result = 1;
}
return result;
}
/* Установка числа строк в каждом барабане */
- (NSInteger) pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component{
NSInteger result = 0;
if ([pickerView isEqual:self.myPicker]){
result = 10; // Или result = [someArray count];
}
return result;
}
/* Установка значений из массива для каждой строки барабана */
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component{
NSString *result = nil;
if ([pickerView isEqual:self.myPicker]){
/* Строки отсчитываются с 0 и мы хотим вывести первую строку, у которой индекс 0 для отрисовки её значения в качестве первой строки. Поэтому мы имеем +1 для каждого индекса строки. */
result = [NSString stringWithFormat:@"Row %ld", (long)row + 1];
}
return result;
}
Крутящиеся барабаны выбора даты и времени через UIDatePicker
Файл Picking_Date_and_Time_with_UIDatePickerViewController.h
#import <UIKit/UIKit.h>
@interface Picking_Date_and_Time_with_UIDatePickerViewController : UIViewController
@property (nonatomic, strong) UIDatePicker *myDatePicker;
@end
Файл Picking_Date_and_Time_with_UIDatePickerViewController.m
#import "Picking_Date_and_Time_with_UIDatePickerViewController.h"
@implementation Picking_Date_and_Time_with_UIDatePickerViewController
@synthesize myDatePicker;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myDatePicker = [[UIDatePicker alloc] init];
self.myDatePicker.center = self.view.center;
/* Перечисление режимов отображения в DatePicker. Просто для примера. */
typedef enum {
UIDatePickerModeTime,
UIDatePickerModeDate,
UIDatePickerModeDateAndTime,
UIDatePickerModeCountDownTimer,
} UIDatePickerMode;
/* Установка режима DatePicker.*/
self.myDatePicker.datePickerMode = UIDatePickerModeDate;
[self.view addSubview:self.myDatePicker];
/* Установка минимальной и максимальной даты. */
NSTimeInterval oneYearTime = 365 * 24 * 60 * 60;
NSDate *todayDate = [NSDate date];
NSDate *oneYearFromToday = [todayDate dateByAddingTimeInterval:oneYearTime];
NSDate *twoYearsFromToday = [todayDate dateByAddingTimeInterval:2 * oneYearTime];
self.myDatePicker.minimumDate = oneYearFromToday;
self.myDatePicker.maximumDate = twoYearsFromToday;
/* Вызов метода datePickerDateChanged при изменении выбранной даты в DatePicker. */
[self.myDatePicker addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
}
/* Метод вывода сообщения при изменении выбранной даты в DatePicker. */
- (void) datePickerDateChanged:(UIDatePicker *)paramDatePicker{
if ([paramDatePicker isEqual:self.myDatePicker]){
NSLog(@"Selected date = %@", paramDatePicker.date);
}
}
@end
/* Получение текущей выбранной даты в DatePicker. */
NSDate *currentDate = self.myDatePicker.date;
NSLog(@"Date = %@", currentDate);
Использование DatePicker в качестве таймера обратного отсчета
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myDatePicker = [[UIDatePicker alloc] init];
self.myDatePicker.center = self.view.center;
/* Установка режима обратного отсчета. */
self.myDatePicker.datePickerMode = UIDatePickerModeCountDownTimer;
[self.view addSubview:self.myDatePicker];
NSTimeInterval twoMinutes = 2 * 60;
[self.myDatePicker setCountDownDuration:twoMinutes];
}
Выбор диапазона значений с помощью слайдера UISlider
Файл Implementing_Range_Pickers_with_UISliderViewController.h
#import <UIKit/UIKit.h>
@interface Implementing_Range_Pickers_with_UISliderViewController
: UIViewController
@property (nonatomic, strong) UISlider *mySlider;
@end
Файл Implementing_Range_Pickers_with_UISliderViewController.m
#import "Implementing_Range_Pickers_with_UISliderViewController.h"
@implementation Implementing_Range_Pickers_with_UISliderViewController
@synthesize mySlider;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.mySlider = [[UISlider alloc] initWithFrame:CGRectMake(0.0f,
0.0f,
200.0f,
23.0f)];
self.mySlider.center = self.view.center;
self.mySlider.minimumValue = 0.0f;
self.mySlider.maximumValue = 100.0f;
self.mySlider.value = self.mySlider.maximumValue / 2.0;
[self.view addSubview:self.mySlider];
/* Метод вывода текущего выбранного значения слайдера при изменении его значения. */
[self.mySlider addTarget:self
action:@selector(sliderValueChanged:)
forControlEvents:UIControlEventValueChanged];
}
/* Метод вывода текущего выбранного значения слайдера. */
- (void) sliderValueChanged:(UISlider *)paramSender{
if ([paramSender isEqual:self.mySlider]){
NSLog(@"New value = %f", paramSender.value);
}
}
@end
/* Для изменения внешнего вида слайдера добавьте следующий код: */
[self.mySlider setThumbImage:[UIImage imageNamed:@"ThumbNormal.png"]
forState:UIControlStateNormal];
[self.mySlider setThumbImage:[UIImage imageNamed:@"ThumbHighlighted.png"]
forState:UIControlStateHighlighted];
Кнопки-вкладки через UISegmentedControl
Файл Grouping_Compact_Options_with_UISegmentedControlViewController.h
#import <UIKit/UIKit.h>
@interface Grouping_Compact_Options_with_UISegmentedControlViewController : UIViewController
@property (nonatomic, strong) UISegmentedControl *mySegmentedControl;
@end
Файл Grouping_Compact_Options_with_UISegmentedControlViewController.m
#import "Grouping_Compact_Options_with_UISegmentedControlViewController.h"
@implementation Grouping_Compact_Options_with_UISegmentedControlViewController
@synthesize mySegmentedControl;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
NSArray *segments = [[NSArray alloc] initWithObjects: @"iPhone",
@"iPad",
@"iPod",
@"iMac",
nil];
self.mySegmentedControl = [[UISegmentedControl alloc] initWithItems:segments];
self.mySegmentedControl.momentary = YES; // Данное значение утсанавливается, если вы хотите, чтобы после нажатия кнопки сразу отжимались обратно, а не фиксировались в положении нажато.
self.mySegmentedControl.center = self.view.center;
[self.view addSubview:self.mySegmentedControl];
/* Метод вывода текущей выбранной вкладки SegmentedControl при переключении. */
[self.mySegmentedControl addTarget:self
action:@selector(segmentChanged:)
forControlEvents:UIControlEventValueChanged];
}
/* Метод получения выбранной вкладки SegmentedControl */
- (void) segmentChanged:(UISegmentedControl *)paramSender{
if ([paramSender isEqual:self.mySegmentedControl]){
NSInteger selectedSegmentIndex = [paramSender selectedSegmentIndex];
NSString *selectedSegmentText = [paramSender titleForSegmentAtIndex:selectedSegmentIndex];
NSLog(@"Segment %ld with %@ text is selected", (long)selectedSegmentIndex, selectedSegmentText);
}
}
@end
Кнопки-вкладки через UISegmentedControl с картинками
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
NSArray *segments = [[NSArray alloc] initWithObjects:
@"iPhone",
[UIImage imageNamed:@"iPad.png"],
@"iPod",
@"iMac",
nil];
self.mySegmentedControl = [[UISegmentedControl alloc] initWithItems:segments];
/* Добавление картинки в кнопку SegmentedControl */
CGRect segmentedFrame = self.mySegmentedControl.frame;
segmentedFrame.size.height = 64.0f;
segmentedFrame.size.width = 300.0f;
self.mySegmentedControl.frame = segmentedFrame;
self.mySegmentedControl.center = self.view.center;
[self.view addSubview:self.mySegmentedControl];
}
/* Изменение стиля SegmentedControl задается через стиль: */
typedef enum {
UISegmentedControlStylePlain,
UISegmentedControlStyleBordered,
UISegmentedControlStyleBar,
UISegmentedControlStyleBezeled,
} UISegmentedControlStyle;
Загрузка View через UINavigationController
Файл Implementing_Navigation_with_UINavigationControllerAppDelegate.h
#import <UIKit/UIKit.h>
@class RootViewController;
@interface Implementing_Navigation_with_UINavigationControllerAppDelegate
: UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) RootViewController *rootViewController;
@end
Файл Implementing_Navigation_with_UINavigationControllerAppDelegate.m
#import "Implementing_Navigation_with_UINavigationControllerAppDelegate.h"
#import "RootViewController.h"
@implementation Implementing_Navigation_with_UINavigationControllerAppDelegate
@synthesize window = _window;
@synthesize navigationController;
@synthesize rootViewController;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
self.rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:NULL];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.rootViewController];
[self.window addSubview:self.navigationController.view];
return YES;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
}
@end
Файл RootViewController.m
#import "RootViewController.h"
#import "SecondViewController.h"
@implementation RootViewController
- (void) pushSecondController{
SecondViewController *secondController = [[SecondViewController alloc] initWithNibName:nil bundle:NULL];
[self.navigationController pushViewController:secondController animated:YES];
}
- (void) viewDidAppear:(BOOL)paramAnimated{
[super viewDidAppear:paramAnimated];
[self performSelector:@selector(pushSecondController) withObject:nil afterDelay:5.0f];
}
@end
Файл SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Second Controller";
}
- (void) goBack{
[self.navigationController popViewControllerAnimated:YES];
}
- (void) viewDidAppear:(BOOL)paramAnimated{
[super viewDidAppear:paramAnimated];
[self performSelector:@selector(goBack) withObject:nil afterDelay:5.0f];
}
@end
Манипулирование загрузкой нескольких View с использованием массива через UINavigationController
Изменение текущего View происходит путем присвоения его значения, прописав его Navigation Controller.
/* Эти методы могут быть вызваны в любом View для смены View. */
/* Первый вариант переключения View */
- (void) goBack{
/* Получить текущий массив View Controllers */
NSArray *currentControllers = self.navigationController.viewControllers;
/* Создать mutable array из полученного выше массива */
NSMutableArray *newControllers = [NSMutableArray arrayWithArray:currentControllers];
/* Удалить последний объект View из массива */
[newControllers removeLastObject];
/* Присвоить массив, прописав его Navigation Controller */
self.navigationController.viewControllers = newControllers
}
/* Второй вариант переключения View */
- (void) goBack{
/* Получить текущий массив View Controllers */
NSArray *currentControllers = self.navigationController.viewControllers;
/* Создать mutable array из полученного выше массива */
NSMutableArray *newControllers = [NSMutableArray arrayWithArray:currentControllers];
/* Удалить последний объект View из массива */
[newControllers removeLastObject];
/* Присвоить массив к Navigation Controller с анимацией */
[self.navigationController setViewControllers:newControllers animated:YES];
}
Отображение картинки на заголовке NavigationBar текущего View
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/* Создание Image View для замены Title View */
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 40.0f)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
/* Загрузить картинку. Будьте осторожны. Эта картинка закэшируется. */
UIImage *image = [UIImage imageNamed:@"FullSizeLogo.png"];
/* Установить картинку для Image View */
[imageView setImage:image];
/*Установить Title для View */
self.navigationItem.titleView = imageView;
}
Добавление кнопок в NavigationBar с использованием UIBarButtonItem
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
/* Добавление кнопки на NavigationBar */
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(performAdd:)];
}
- (void) performAdd:(id)paramSender{
NSLog(@"Action method got called.");
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
/* Добавление кнопки на NavigationBar */
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(performAdd:)];
}
- (void) performAdd:(id)paramSender{
NSLog(@"Action method got called.");
}
/* Типы кнопок, которые могут быть выведены на NavigationBar */
typedef enum {
UIBarButtonSystemItemDone,
UIBarButtonSystemItemCancel,
UIBarButtonSystemItemEdit,
UIBarButtonSystemItemSave,
UIBarButtonSystemItemAdd,
UIBarButtonSystemItemFlexibleSpace,
UIBarButtonSystemItemFixedSpace,
UIBarButtonSystemItemCompose,
UIBarButtonSystemItemReply,
UIBarButtonSystemItemAction,
UIBarButtonSystemItemOrganize,
UIBarButtonSystemItemBookmarks,
UIBarButtonSystemItemSearch,
UIBarButtonSystemItemRefresh,
UIBarButtonSystemItemStop,
UIBarButtonSystemItemCamera,
UIBarButtonSystemItemTrash,
UIBarButtonSystemItemPlay,
UIBarButtonSystemItemPause,
UIBarButtonSystemItemRewind,
UIBarButtonSystemItemFastForward,
UIBarButtonSystemItemUndo,
UIBarButtonSystemItemRedo,
UIBarButtonSystemItemPageCurl,
} UIBarButtonSystemItem;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
UISwitch *simpleSwitch = [[UISwitch alloc] init];
simpleSwitch.on = YES;
[simpleSwitch addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:simpleSwitch];
}
- (void) switchIsChanged:(UISwitch *)paramSender{
if ([paramSender isOn]){
NSLog(@"Switch is on.");
} else {
NSLog(@"Switch is off.");
}
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First Controller";
NSArray *items = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"UpArrow.png"], [UIImage imageNamed:@"DownArrow.png"], nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
[segmentedControl addTarget:self action:@selector(segmentedControlTapped:) forControlEvents:UIControlEventValueChanged];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
}
- (void) segmentedControlTapped:(UISegmentedControl *)paramSender{
if ([paramSender selectedSegmentIndex] == 0){
/* Кнопка Вверх */
NSLog(@"Up");
} else if ([paramSender selectedSegmentIndex] == 1){
/* Кнопка Вниз */
NSLog(@"Down");
}
}
Кнопки-вкладки через UITabBarController
Файл Presenting_Multiple_View_Controllers_with_UITabBarControllerAppDelegate.h
#import <UIKit/UIKit.h>
@class FirstViewController;
@class SecondViewController;
@interface Presenting_Multiple_View_Controllers_with_UITabBarControllerAppDelegate
: UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) FirstViewController *firstViewController;
@property (nonatomic, strong) UINavigationController *firstNavigationController;
@property (nonatomic, strong) SecondViewController *secondViewController;
@property (nonatomic, strong) UINavigationController *secondNavigationController;
@property (nonatomic, strong) UITabBarController *tabBarController;
@end
Файл Presenting_Multiple_View_Controllers_with_UITabBarControllerAppDelegate.m
#import "Presenting_Multiple_View_Controllers_with_UITabBarControllerAppDelegate.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation Presenting_Multiple_View_Controllers_with_UITabBarControllerAppDelegate
@synthesize window = _window;
@synthesize firstViewController;
@synthesize firstNavigationController;
@synthesize secondViewController;
@synthesize secondNavigationController;
@synthesize tabBarController;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
/* Точка перезагрузки кастомизации после запуска приложения. */
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
self.firstViewController = [[FirstViewController alloc] initWithNibName:nil bundle:NULL];
self.firstNavigationController =[[UINavigationController alloc] initWithRootViewController:self.firstViewController];
self.secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:NULL];
self.secondNavigationController = [[UINavigationController alloc] initWithRootViewController:self.secondViewController];
NSArray *twoNavControllers = [[NSArray alloc] initWithObjects: self.firstNavigationController, self.secondNavigationController, nil];
self.tabBarController = [[UITabBarController alloc] init];
[self.tabBarController setViewControllers:twoNavControllers];
[self.window addSubview:self.tabBarController.view];
return YES;
}
@end
Файл FirstViewController.m
#import "FirstViewController.h"
@implementation FirstViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil) {
self.title = @"First";
}
return self;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
@end
Файл SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil) {
self.title = @"Second";
}
return self;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
@end
Добавление картинок в кнопки-вкладки через UITabBarController
Файл FirstViewController.m
#import "FirstViewController.h"
@implementation FirstViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil) {
self.title = @"First";
self.tabBarItem.image = [UIImage imageNamed:@"FirstTab.png"];
}
return self;
}
@end
Файл SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil) {
self.title = @"Second";
self.tabBarItem.image = [UIImage imageNamed:@"SecondTab.png"];
}
return self;
}
@end
Отображение статичного текста чере UILabel
Файл Displaying_Static_Text_with_UILabelViewController.h
#import <UIKit/UIKit.h>
@interface Displaying_Static_Text_with_UILabelViewController : UIViewController
@property (nonatomic, strong) UILabel *myLabel;
@end
Файл Displaying_Static_Text_with_UILabelViewController.m
#import "Displaying_Static_Text_with_UILabelViewController.h"
@implementation Displaying_Static_Text_with_UILabelViewController
@synthesize myLabel;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
CGRect labelFrame = CGRectMake(0.0f,
0.0f,
100.0f,
50.0f);
self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.myLabel.text = @"iOS 5 Programming Cookbook";
self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f];
self.myLabel.numberOfLines = 3;
self.myLabel.center = self.view.center;
[self.view addSubview:self.myLabel];
}
@end
/* Если необходимо, чтобы рамка label оставалась статичной, а шрифт внутри label мог растягиваться до границ label , то надо установить свойство adjustsFontSizeToFitWidth в значение YES. Для примера, если значение height нашей label было 23.0f, то мы можем растянуть текст в до границ label. */
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
CGRect labelFrame = CGRectMake(0.0f,
0.0f,
100.0f,
23.0f);
self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.myLabel.adjustsFontSizeToFitWidth = YES;
self.myLabel.text = @"iOS 5 Programming Cookbook";
self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f];
self.myLabel.center = self.view.center;
[self.view addSubview:self.myLabel];
}
Поле текстового ввода через UITextField
Файл Accepting_User_Text_Input_with_UITextFieldViewController.h
#import <UIKit/UIKit.h>
@interface Accepting_User_Text_Input_with_UITextFieldViewController : UIViewController
@property (nonatomic, strong) UITextField *myTextField;
@end
Файл Accepting_User_Text_Input_with_UITextFieldViewController.m
#import "Accepting_User_Text_Input_with_UITextFieldViewController.h"
@implementation Accepting_User_Text_Input_with_UITextFieldViewController
@synthesize myTextField;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
CGRect textFieldFrame = CGRectMake(0.0f,
0.0f,
200.0f,
31.0f);
self.myTextField = [[UITextField alloc] initWithFrame:textFieldFrame];
self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.myTextField.textAlignment = UITextAlignmentCenter;
self.myTextField.text = @"Sir Richard Branson";
self.myTextField.center = self.view.center;
[self.view addSubview:self.myTextField];
}
@end
Редактирование текстового поля чере UITextField с помощью клавиатуры
Файл Accepting_User_Text_Input_with_UITextFieldViewController.h
#import <UIKit/UIKit.h>
@interface Accepting_User_Text_Input_with_UITextFieldViewController
: UIViewController <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *myTextField;
@property (nonatomic, strong) UILabel *labelCounter;
@end
Файл Accepting_User_Text_Input_with_UITextFieldViewController.m
#import "Accepting_User_Text_Input_with_UITextFieldViewController.h"
@implementation Accepting_User_Text_Input_with_UITextFieldViewController
@synthesize myTextField;
@synthesize labelCounter;
- (void) calculateAndDisplayTextFieldLengthWithText:(NSString *)paramText{
NSString *characterOrCharacters = @"Characters";
if ([paramText length] == 1){
characterOrCharacters = @"Character";
}
self.labelCounter.text = [NSString stringWithFormat: @"%lu %@", (unsigned long)[paramText length], characterOrCharacters];
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
BOOL result = YES;
if ([textField isEqual:self.myTextField]){
NSString *wholeText = [textField.text stringByReplacingCharactersInRange:range
withString:string];
[self calculateAndDisplayTextFieldLengthWithText:wholeText];
}
return result;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
CGRect textFieldFrame = CGRectMake(38.0f,
30.0f,
220.0f,
31.0f);
self.myTextField = [[UITextField alloc] initWithFrame:textFieldFrame];
self.myTextField.delegate = self;
self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.myTextField.textAlignment = UITextAlignmentCenter;
self.myTextField.text = @"Sir Richard Branson";
[self.view addSubview:self.myTextField];
CGRect labelCounterFrame = self.myTextField.frame;
labelCounterFrame.origin.y += textFieldFrame.size.height + 10;
self.labelCounter = [[UILabel alloc] initWithFrame:labelCounterFrame];
[self.view addSubview:self.labelCounter];
[self calculateAndDisplayTextFieldLengthWithText:self.myTextField.text];
}
@end
/* Пример кода помещения надписи плейсхолдера в текстовое поле. */
self.myTextField = [[UITextField alloc] initWithFrame:textFieldFrame];
self.myTextField.delegate = self;
self.myTextField.borderStyle = UITextBorderStyleRoundedRect;
self.myTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.myTextField.textAlignment = UITextAlignmentCenter;
self.myTextField.placeholder = @"Enter text here...";
[self.view addSubview:self.myTextField];
/* Заполнение текстового символами поля слева и справа от ввода данных. */
UILabel *currencyLabel = [[UILabel alloc] initWithFrame:CGRectZero];
currencyLabel.text = [[[NSNumberFormatter alloc] init] currencySymbol];
currencyLabel.font = self.myTextField.font;
[currencyLabel sizeToFit];
self.myTextField.leftView = currencyLabel;
self.myTextField.leftViewMode = UITextFieldViewModeAlways;
/* Типы отображения поля ввода. */
typedef enum {
UITextFieldViewModeNever,
UITextFieldViewModeWhileEditing,
UITextFieldViewModeUnlessEditing,
UITextFieldViewModeAlways
} UITextFieldViewMode;
Размещение больших фрагментов текста в текстовом поле через UITextView
Файл Displaying_Long_Lines_of_Text_with_UITextViewViewController.h
#import <UIKit/UIKit.h>
@interface Displaying_Long_Lines_of_Text_with_UITextViewViewController
: UIViewController
@property (nonatomic, strong) UITextView *myTextView;
@end
Файл Displaying_Long_Lines_of_Text_with_UITextViewViewController.m
#import "Displaying_Long_Lines_of_Text_with_UITextViewViewController.h"
@implementation Displaying_Long_Lines_of_Text_with_UITextViewViewController
@synthesize myTextView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
self.myTextView.text = @"Some text here...";
self.myTextView.font = [UIFont systemFontOfSize:16.0f];
[self.view addSubview:self.myTextView];
}
- (void) handleKeyboardDidShow:(NSNotification *)paramNotification{
/* Получить рамку клавиатуры */
NSValue *keyboardRectAsObject = [[paramNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
/* Поместить значение рамки в CGRect */
CGRect keyboardRect;
[keyboardRectAsObject getValue:&keyboardRect];
/* Сделать отступ снизу для нашего текстового поля ввода на величину высоты клавиатуры. */
self.myTextView.contentInset = UIEdgeInsetsMake(0.0f,
0.0f,
keyboardRect.size.height,
0.0f);
}
- (void) handleKeyboardWillHide:(NSNotification *)paramNotification{
/* Опять сделать о текстовое поле по высоте экрана */
self.myTextView.contentInset = UIEdgeInsetsZero;
}
- (void) viewWillAppear:(BOOL)paramAnimated{
[super viewWillAppear:paramAnimated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
self.view.backgroundColor = [UIColor whiteColor];
self.myTextView = [[UITextView alloc] initWithFrame:self.view.bounds];
self.myTextView.text = @"Some text here...";
self.myTextView.font = [UIFont systemFontOfSize:16.0f];
[self.view addSubview:self.myTextView];
}
- (void) viewWillDisappear:(BOOL)paramAnimated{
[super viewWillDisappear:paramAnimated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
Простая кнопка через UIButton
Файл Adding_Buttons_to_the_User_Interface_with_UIButtonViewController.h
#import <UIKit/UIKit.h>
@interface Adding_Buttons_to_the_User_Interface_with_UIButtonViewController : UIViewController
@property (nonatomic, strong) UIButton *myButton;
@end
Файл Adding_Buttons_to_the_User_Interface_with_UIButtonViewController.m
#import "Adding_Buttons_to_the_User_Interface_with_UIButtonViewController.h"
@implementation
Adding_Buttons_to_the_User_Interface_with_UIButtonViewController
@synthesize myButton;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.myButton.frame = CGRectMake(110.0f,
200.0f,
100.0f,
37.0f);
[self.myButton setTitle:@"Press Me" forState:UIControlStateNormal];
[self.myButton setTitle:@"I'm Pressed" forState:UIControlStateHighlighted];
[self.myButton addTarget:self action:@selector(buttonIsPressed:) forControlEvents:UIControlEventTouchDown];
[self.myButton addTarget:self action:@selector(buttonIsTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.myButton];
}
- (void) buttonIsPressed:(UIButton *)paramSender{
NSLog(@"Button is pressed.");
}
- (void) buttonIsTapped:(UIButton *)paramSender{
NSLog(@"Button is tapped.");
}
@end
/* Типы простых кнопок. */
typedef enum {
UIButtonTypeCustom = 0,
UIButtonTypeRoundedRect,
UIButtonTypeDetailDisclosure,
UIButtonTypeInfoLight,
UIButtonTypeInfoDark,
UIButtonTypeContactAdd,
} UIButtonType;
Простая кнопка через UIButton в виде картинки
UIImage *normalImage = [UIImage imageNamed:@"NormalBlueButton.png"];
UIImage *highlightedImage = [UIImage imageNamed:@"HighlightedBlueButton"];
self.myButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.myButton.frame = CGRectMake(110.0f,
200.0f,
100.0f,
37.0f);
[self.myButton setBackgroundImage:normalImage forState:UIControlStateNormal];
[self.myButton setTitle:@"Normal" forState:UIControlStateNormal];
[self.myButton setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
[self.myButton setTitle:@"Pressed" forState:UIControlStateHighlighted];
Отображение картинок через UIImageView
Файл Displaying_Images_with_UIImageViewViewController.h
#import <UIKit/UIKit.h>
@interface Displaying_Images_with_UIImageViewViewController : UIViewController
@property (nonatomic, strong) UIImageView *myImageView;
@end
Файл Displaying_Images_with_UIImageViewViewController.m
#import "Displaying_Images_with_UIImageViewViewController.h"
@implementation Displaying_Images_with_UIImageViewViewController
@synthesize myImageView;
- (void)viewDidLoad{
[super viewDidLoad];
UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
self.myImageView = [[UIImageView alloc] initWithImage:macBookAir];
self.myImageView.center = self.view.center;
[self.view addSubview:self.myImageView];
}
@end
/* Точная установка ширины и высоты картинки */
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
self.myImageView = [[UIImageView alloc] initWithImage:macBookAir];
self.myImageView.center = self.view.center;
[self.view addSubview:self.myImageView];
}
/* Варианты типов масштабирования картинки через UIImageView */
typedef enum {
UIViewContentModeScaleToFill,
UIViewContentModeScaleAspectFit,
UIViewContentModeScaleAspectFill,
UIViewContentModeRedraw,
UIViewContentModeCenter,
UIViewContentModeTop,
UIViewContentModeBottom,
UIViewContentModeLeft,
UIViewContentModeRight,
UIViewContentModeTopLeft,
UIViewContentModeTopRight,
UIViewContentModeBottomLeft,
UIViewContentModeBottomRight,
} UIViewContentMode;
/* Пример применения масштабирования картинки через UIImageView */
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
self.myImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
self.myImageView.image = macBookAir;
self.myImageView.image = UIViewContentModeScaleAspectFill;
self.myImageView.center = self.view.center;
[self.view addSubview:self.myImageView];
}
Прокручивание всего содержимого через UIScrollView
Файл Creating_Scrollable_Content_with_UIScrollViewViewController.h
#import <UIKit/UIKit.h>
@interface Creating_Scrollable_Content_with_UIScrollViewViewController : UIViewController <UIScrollViewDelegate>
@property (nonatomic, strong) UIImageView *myImageView;
@property (nonatomic, strong) UIScrollView *myScrollView;
@end
Файл Creating_Scrollable_Content_with_UIScrollViewViewController.m
#import "Creating_Scrollable_Content_with_UIScrollViewViewController.h"
@implementation Creating_Scrollable_Content_with_UIScrollViewViewController
@synthesize myImageView;
@synthesize myScrollView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIImage *imageToLoad = [UIImage imageNamed:@"MacBookAir.png"];
self.myImageView = [[UIImageView alloc] initWithImage:imageToLoad];
self.myScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
[self.myScrollView addSubview:self.myImageView];
self.myScrollView.contentSize = self.myImageView.bounds.size;
self.myScrollView.delegate = self;
[self.view addSubview:self.myScrollView];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
/* Данный метод вызывается когда пользователь прокручивает или тащит изображение. */
self.myScrollView.alpha = 0.50f;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
/* Данный метод используется только после завершения прокручивания. */
self.myScrollView.alpha = 1.0f;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
/* Убедитесь в том, что alpha обязательно переустановлена, если пользователь тянет. */
self.myScrollView.alpha = 1.0f;
}
@end
/* Пример изменения цвета индикатора прокрутки на белый */
self.myScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
/* Включение режима горизонтальной прокрути pagination через UIScrollView */
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UIImage *iPhone = [UIImage imageNamed:@"iPhone.png"];
UIImage *iPad = [UIImage imageNamed:@"iPad.png"];
UIImage *macBookAir = [UIImage imageNamed:@"MacBookAir.png"];
CGRect scrollViewRect = self.view.bounds;
self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollViewRect];
self.myScrollView.pagingEnabled = YES;
self.myScrollView.contentSize = CGSizeMake(scrollViewRect.size.width * 3.0f, scrollViewRect.size.height);
[self.view addSubview:self.myScrollView];
CGRect imageViewRect = self.view.bounds;
UIImageView *iPhoneImageView = [self newImageViewWithImage:iPhone
frame:imageViewRect];
[self.myScrollView addSubview:iPhoneImageView];
/* Переход к следующей странице через перемещение по оси x к следующей картинке. */
imageViewRect.origin.x += imageViewRect.size.width;
UIImageView *iPadImageView = [self newImageViewWithImage:iPad
frame:imageViewRect];
[self.myScrollView addSubview:iPadImageView];
/*Переход к следующей странице через перемещение по оси x к следующей картинке. */
imageViewRect.origin.x += imageViewRect.size.width;
UIImageView *macBookAirImageView = [self newImageViewWithImage:macBookAir frame:imageViewRect];
[self.myScrollView addSubview:macBookAirImageView];
}
Загрузка интернет-страниц через UIWebView
Файл Loading_Web_Pages_with_UIWebViewViewController.h
#import <UIKit/UIKit.h>
@interface Loading_Web_Pages_with_UIWebViewViewController : UIViewController
@property (nonatomic, strong) UIWebView *myWebView;
@end
Файл Loading_Web_Pages_with_UIWebViewViewController.m
#import "Loading_Web_Pages_with_UIWebViewViewController.h"
@implementation Loading_Web_Pages_with_UIWebViewViewController
@synthesize myWebView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:self.myWebView];
NSString *htmlString = @"iOS 5 Programming <strong>Cookbook</strong>";
[self.myWebView loadHTMLString:htmlString baseURL:nil];
}
@end
/* Загрузка интернет-страницы по адресу URL */
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
self.myWebView.scalesPageToFit = YES;
[self.view addSubview:self.myWebView];
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request];
}
/* Добавление индикатора загрузки интернет-страницы */
Файл Loading_Web_Pages_with_UIWebViewViewController.h
#import <UIKit/UIKit.h>
@interface Loading_Web_Pages_with_UIWebViewViewController : UIViewController <UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *myWebView;
@end
Файл Loading_Web_Pages_with_UIWebViewViewController.m
#import "Loading_Web_Pages_with_UIWebViewViewController.h"
@implementation Loading_Web_Pages_with_UIWebViewViewController
@synthesize myWebView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];
self.myWebView.delegate = self;
self.myWebView.scalesPageToFit = YES;
[self.view addSubview:self.myWebView];
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request];
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
@end
Отображение Popover через UIPopoverController на iPad
#import <UIKit/UIKit.h>
@class Displaying_Popovers_with_UIPopoverControllerViewController;
@interface Displaying_Popovers_with_UIPopoverControllerAppDelegate
: UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) Displaying_Popovers_with_UIPopoverControllerViewController *viewController;
@property (nonatomic, strong) UINavigationController *navigationController;
@end
#import "Displaying_Popovers_with_UIPopoverControllerAppDelegate.h"
#import "Displaying_Popovers_with_UIPopoverControllerViewController.h"
@implementation Displaying_Popovers_with_UIPopoverControllerAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize navigationController;
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
UIUserInterfaceIdiom uiIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
NSString *viewControllerClass = @"Displaying_Popovers_with_UIPopoverControllerViewController_iPad";
if (uiIdiom == UIUserInterfaceIdiomPhone) {
viewControllerClass = @"Displaying_Popovers_with_UIPopoverControllerViewController_iPhone";
}
self.viewController = [[Displaying_Popovers_with_UIPopoverControllerViewController alloc] initWithNibName:viewControllerClass bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
#import <UIKit/UIKit.h>
@interface Displaying_Popovers_with_UIPopoverControllerViewController
: UIViewController <UIAlertViewDelegate>
@property (nonatomic, strong) UIPopoverController *popoverController;
@property (nonatomic, strong) UIBarButtonItem *barButtonAdd;
@end
#import "Displaying_Popovers_with_UIPopoverControllerViewController.h"
#import "PopoverContentViewController.h"
@implementation Displaying_Popovers_with_UIPopoverControllerViewController
@synthesize popoverController;
@synthesize barButtonAdd;
- (void)viewDidLoad{
[super viewDidLoad];
/* Проверка существует ли данный класс в iOS */
Class popoverClass = NSClassFromString(@"UIPopoverController");
if (popoverClass != nil && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
PopoverContentViewController *content = [[PopoverContentViewController alloc] initWithNibName:nil bundle:nil];
self.popoverController = [[UIPopoverController alloc] initWithContentViewController:content];
content.popoverController = self.popoverController;
self.barButtonAdd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(performAddWithPopover:)];
} else {
self.barButtonAdd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(performAddWithAlertView:)];
}
[self.navigationItem setRightBarButtonItem:self.barButtonAdd animated:NO];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.barButtonAdd = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation
:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
- (NSString *) photoButtonTitle{
return @"Photo";
}
- (NSString *) audioButtonTitle{
return @"Audio";
}
- (void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
if ([buttonTitle isEqualToString:[self photoButtonTitle]]){
/* Добавление фото. */
} else if ([buttonTitle isEqualToString:[self audioButtonTitle]]){
/* Добавление аудио */
}
}
- (void) performAddWithAlertView:(id)paramSender{
[[[UIAlertView alloc] initWithTitle:nilи message:@"Add..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: [self photoButtonTitle], [self audioButtonTitle], nil] show];
}
- (void) performAddWithPopover:(id)paramSender{
[self.popoverController presentPopoverFromBarButtonItem:self.barButtonAdd permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
@end
#import <UIKit/UIKit.h>
@interface PopoverContentViewController : UIViewController
@property (nonatomic, strong) UIButton *buttonPhoto;
@property (nonatomic, strong) UIButton *buttonAudio;
/* Мы не должны определять это свойство, как strong. Иначе это создаст цикл retain между popover controller и content view controller из-за того, что
popover controller делает retain content view controller и поэтому view controller будет делать retain popover controller */
@property (nonatomic, weak) UIPopoverController *popoverController;
@end
#import "PopoverContentViewController.h"
@implementation PopoverContentViewController
@synthesize buttonPhoto;
@synthesize buttonAudio;
@synthesize popoverController;
- (BOOL) isInPopover{
Class popoverClass = NSClassFromString(@"UIPopoverController");
if (popoverClass != nil && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.popoverController != nil){
return YES;
} else {
return NO;
}
}
- (void) gotoAppleWebsite:(id)paramSender{
if ([self isInPopover]){
/* Переход на интернет-сайт и отпускание popover */
[self.popoverController dismissPopoverAnimated:YES];
} else {
/* Код для iPhone */
}
}
- (void) gotoAppleStoreWebsite:(id)paramSender{
if ([self isInPopover]){
/* Переход на интернет-сайт и отпускание popover */
[self.popoverController dismissPopoverAnimated:YES];
} else {
/* Код для iPhone */
}
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.contentSizeForViewInPopover = CGSizeMake(200.0f, 125.0f);
CGRect buttonRect = CGRectMake(20.0f,
20.0f,
160.0f,
37.0f);
self.buttonPhoto = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.buttonPhoto setTitle:@"Photo" forState:UIControlStateNormal];
[self.buttonPhoto addTarget:self action:@selector(gotoAppleWebsite:) forControlEvents:UIControlEventTouchUpInside];
self.buttonPhoto.frame = buttonRect;
[self.view addSubview:self.buttonPhoto];
buttonRect.origin.y += 50.0f;
self.buttonAudio = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.buttonAudio setTitle:@"Audio" forState:UIControlStateNormal];
[self.buttonAudio addTarget:self action:@selector(gotoAppleStoreWebsite:) forControlEvents:UIControlEventTouchUpInside];
self.buttonAudio.frame = buttonRect;
[self.view addSubview:self.buttonAudio];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.buttonPhoto = nil;
self.buttonAudio = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation
:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
@end
/* Перечень возможных направлений появления Popover */
enum {
UIPopoverArrowDirectionUp = 1UL << 0,
UIPopoverArrowDirectionDown = 1UL << 1,
UIPopoverArrowDirectionLeft = 1UL << 2,
UIPopoverArrowDirectionRight = 1UL << 3,
UIPopoverArrowDirectionAny = UIPopoverArrowDirectionUp |
UIPopoverArrowDirectionDown |
UIPopoverArrowDirectionLeft |
UIPopoverArrowDirectionRight,
UIPopoverArrowDirectionUnknown = NSUIntegerMax
};
typedef NSUInteger UIPopoverArrowDirection;
Отображение прогресс-бара через UIProgressView
Файл ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) UIProgressView *progressView;
@end
Файл ViewController.m
#import "ViewController.h"
@implementation ViewController
@synthesize progressView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
self.progressView.center = self.view.center;
self.progressView.progress = 0.5f;
[self.view addSubview:self.progressView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.progressView = nil;
}
@end
Таблица через UITableView
Файл Populating_a_Table_View_with_DataViewController.h
#import <UIKit/UIKit.h>
@interface Populating_a_Table_View_with_DataViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *myTableView;
@end
Файл Populating_a_Table_View_with_DataViewController.m
#import "Populating_a_Table_View_with_DataViewController.h"
@implementation Populating_a_Table_View_with_DataViewController
@synthesize myTableView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
/* Убедимся, что таблица корректно масштабируется */
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
[self.view addSubview:self.myTableView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myTableView = nil;
}
/* Устанавливаем число колонок в таблице */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]){
result = 3;
}
return result;
}
/* Устанавливаем число строк в таблице */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]){
switch (section){
case 0:{
result = 3;
break;
}
case 1:{
result = 5;
break;
}
case 2:{
result = 8;
break;
}
}
}
return result;
}
/* Устанавливаем содержимое каждой ячейки таблицы */
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *result = nil;
if ([tableView isEqual:self.myTableView]){
static NSString *TableViewCellIdentifier = @"MyCells";
result = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableViewCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld", (long)indexPath.section, (long)indexPath.row];
}
return result;
}
/* Устанавливаем действие на клик по ячейке таблицы */
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if ([tableView isEqual:self.myTableView]){
NSLog(@"%@", [NSString stringWithFormat:@"Cell %ld in Section %ld is selected", (long)indexPath.row, (long)indexPath.section]);
}
}
@end
Добавление иконок в строки таблицы через UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* result = nil;
if ([tableView isEqual:self.myTableView]){
static NSString *MyCellIdentifier = @"SimpleCell";
/* Мы попытаемся получить существующую ячейку с по данному идентификатору. */
result = [tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
if (result == nil){
/* Если ячейка с данным идентификатором не существует, то мы создадим ячейку с идентификатором и передадим её в table view */
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld", (long)indexPath.section, (long)indexPath.row];
result.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
return result;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds
style:UITableViewStylePlain];
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myTableView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myTableView = nil;
}
- (void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
/* Сделать что-то, если нажмут на иконку accessory button в строке таблицы */
NSLog(@"Accessory button is tapped for cell at index path = %@", indexPath);
UITableViewCell *ownerCell = [tableView cellForRowAtIndexPath:indexPath];
NSLog(@"Cell Title = %@", ownerCell.textLabel.text);
}
Добавление собственной картинки-иконки в строки таблицы через UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* result = nil;
static NSString *MyCellIdentifier = @"SimpleCell";
/* Мы попытаемся получить существующую ячейку с по данному идентификатору. */
result = [tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld", (long)indexPath.section, (long)indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0.0f, 0.0f, 150.0f, 25.0f);
[button setTitle:@"Expand" forState:UIControlStateNormal];
[button addTarget:self action:@selector(performExpand:)
forControlEvents:UIControlEventTouchUpInside];
result.accessoryView = button;
return result;
}
- (void) performExpand:(UIButton *)paramSender{
UITableViewCell *ownerCell = (UITableViewCell*)paramSender.superview;
if (ownerCell != nil){
/* Здесь мы получаем индекс ячейки, содержащей секцию и строку */
NSIndexPath *ownerCellIndexPath = [self.myTableView indexPathForCell:ownerCell];
NSLog(@"Accessory in index path is tapped. Index path = %@", ownerCellIndexPath);
/* Здесь мы можем использоватьэти два значения, чтобы полностью определить, какая accessory button была инициатором события нажатия:
OwnerCellIndexPath.section
OwnerCellIndexPath.row
*/
if (ownerCellIndexPath.section == 0 && ownerCellIndexPath.row == 1){
/* Это вторая строка в первой секции. */
}
/* И так далее с проверкой других строк ... */
}
}
Ступенчатое отображение данных в таблице через UITableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* result = nil;
static NSString *MyCellIdentifier = @"SimpleCells";
result = [tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCellIdentifier];
}
result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld", (long)indexPath.section, (long)indexPath.row];
result.indentationLevel = indexPath.row;
result.indentationWidth = 10.0f;
return result;
}
Включение функции удаления строк таблицы через UITableView
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;
if ([tableView isEqual:self.myTableView]){
result = UITableViewCellEditingStyleDelete;
}
return result;
}
- (void) setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
[self.myTableView setEditing:editing animated:animated];
}
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete){
if (indexPath.row < [self.arrayOfRows count]){
/* Сперва удалим объект из источника данных для таблицы */
[self.arrayOfRows removeObjectAtIndex:indexPath.row];
/* Затем удалим ячейку из Table View */
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}
}
Создание Header и Footer для таблицы через UITableView
Файл Constructing_Headers_and_Footers_in_Table_ViewsViewController.h
#import <UIKit/UIKit.h>
@interface Constructing_Headers_and_Footers_in_Table_ViewsViewController
: UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@end
Файл Constructing_Headers_and_Footers_in_Table_ViewsViewController.m
#import "Constructing_Headers_and_Footers_in_Table_ViewsViewController.h"
@implementation Constructing_Headers_and_Footers_in_Table_ViewsViewController
@synthesize myTableView;
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
static NSString *CellIdentifier = @"CellIdentifier";
result = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
result.textLabel.text = [[NSString alloc] initWithFormat:@"Cell %ld", (long)indexPath.row];
return result;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.myTableView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation :(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *result = nil;
if ([tableView isEqual:self.myTableView] && section == 0){
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.text = @"Section 1 Header";
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
/* Сдвинуть метку на 10 пикселей вправо */
label.frame = CGRectMake(label.frame.origin.x + 10.0f,
5.0f, /* Сдвинуть метку на 5 пикселей вниз */
label.frame.size.width,
label.frame.size.height);
/* Сделать container view на 10 пикселей больше по ширине, чем наша label из-за того, что label нужно на 10 пикселей большеотступа слева */
CGRect resultFrame = CGRectMake(0.0f,
0.0f,
label.frame.size.height,
label.frame.size.width + 10.0f);
result = [[UIView alloc] initWithFrame:resultFrame];
[result addSubview:label];
}
return result;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UIView *result = nil;
if ([tableView isEqual:self.myTableView] && section == 0){
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.text = @"Section 1 Footer";
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
/* Сдвинуть метку на 10 пикселей вправо */
label.frame = CGRectMake(label.frame.origin.x + 10.0f,
5.0f, /* Сдвинуть метку на 5 пикселей вниз */
label.frame.size.width,
label.frame.size.height);
/* Сделать container view на 10 пикселей больше по ширине, чем наша label из-за того, что label нужно на 10 пикселей большеотступа слева */
CGRect resultFrame = CGRectMake(0.0f,
0.0f,
label.frame.size.height,
label.frame.size.width + 10.0f);
result = [[UIView alloc] initWithFrame:resultFrame];
[result addSubview:label];
}
return result;
}
- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
NSString *result = nil;
if ([tableView isEqual:self.myTableView] && section == 0){
result = @"Section 1 Header";
}
return result;
}
- (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
NSString *result = nil;
if ([tableView isEqual:self.myTableView] && section == 0){
result = @"Section 1 Footer";
}
return result;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
CGFloat result = 0.0f;
if ([tableView isEqual:self.myTableView] && section == 0){
result = 30.0f;
}
return result;
}
- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
CGFloat result = 0.0f;
if ([tableView isEqual:self.myTableView] && section == 0){
result = 30.0f;
}
return result;
}
@end
Отображение меню над строкой таблицы через UITableView
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 3;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
static NSString *CellIdentifier = @"CellIdentifier";
result = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
result.textLabel.text = [[NSString alloc] initWithFormat:@"Section %ld Cell %ld", (long)indexPath.section, (long)indexPath.row];
return result;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
[self.view addSubview:self.myTableView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myTableView = nil;
}
- (BOOL) tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
/* Разрешено показывать всплывающее меню над каждой строкой таблицы */
return YES;
}
- (BOOL) tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
if (action == @selector(copy:)){
return YES;
}
return NO;
}
- (void) tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
if (action == @selector(copy:)){
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
[pasteBoard setString:cell.textLabel.text];
}
}
Перемещение строк и колонок таблицы через UITableView
Файл Moving_Cells_and_Sections_in_Table_ViewsViewController.h
#import <UIKit/UIKit.h>
@interface Moving_Cells_and_Sections_in_Table_ViewsViewController
: UIViewController <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *myTableView;
/* Каждая секция представляет собой массив, содержащий объекты типа NSString */
@property (nonatomic, strong) NSMutableArray *arrayOfSections;
@end
Файл Moving_Cells_and_Sections_in_Table_ViewsViewController.m
#import "Moving_Cells_and_Sections_in_Table_ViewsViewController.h"
@implementation Moving_Cells_and_Sections_in_Table_ViewsViewController
@synthesize myTableView;
@synthesize arrayOfSections;
- (NSMutableArray *) newSectionWithIndex:(NSUInteger)paramIndex
withCellCount:(NSUInteger)paramCellCount{
NSMutableArray *result = [[NSMutableArray alloc] init];
NSUInteger counter = 0;
for (counter = 0;
counter < paramCellCount;
counter++){
[result addObject:[[NSString alloc] initWithFormat:@"Section %lu Cell %lu", (unsigned long)paramIndex, (unsigned long)counter+1]];
}
return result;
}
- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self != nil){
arrayOfSections = [[NSMutableArray alloc] init];
NSMutableArray *section1 = [self newSectionWithIndex:1 withCellCount:3];
NSMutableArray *section2 = [self newSectionWithIndex:2 withCellCount:3];
NSMutableArray *section3 = [self newSectionWithIndex:3 withCellCount:3];
[arrayOfSections addObject:section1];
[arrayOfSections addObject:section2];
[arrayOfSections addObject:section3];
}
return self;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]){
result = (NSInteger)[self.arrayOfSections count];
}
return result;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSInteger result = 0;
if ([tableView isEqual:self.myTableView]){
if ([self.arrayOfSections count] > section){
NSMutableArray *sectionArray = [self.arrayOfSections objectAtIndex:section];
result = (NSInteger)[sectionArray count];
}
}
return result;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *result = nil;
if ([tableView isEqual:self.myTableView]){
static NSString *CellIdentifier = @"CellIdentifier";
result = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (result == nil){
result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSMutableArray *sectionArray = [self.arrayOfSections objectAtIndex:indexPath.section];
result.textLabel.text = [sectionArray objectAtIndex:indexPath.row];
}
return result;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myTableView = nil;
}
- (void) moveSection1ToSection3{
NSMutableArray *section1 = [self.arrayOfSections objectAtIndex:0];
[self.arrayOfSections removeObject:section1];
[self.arrayOfSections addObject:section1];
[self.myTableView moveSection:0 toSection:2];
}
- (void) moveCell1InSection1ToCell2InSection1{
NSMutableArray *section1 = [self.arrayOfSections objectAtIndex:0];
NSString *cell1InSection1 = [section1 objectAtIndex:0];
[section1 removeObject:cell1InSection1];
[section1 insertObject:cell1InSection1 atIndex:1];
NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
[self.myTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
}
- (void) moveCell2InSection1ToCell1InSection2{
NSMutableArray *section1 = [self.arrayOfSections objectAtIndex:0];
NSMutableArray *section2 = [self.arrayOfSections objectAtIndex:1];
NSString *cell2InSection1 = [section1 objectAtIndex:1];
[section1 removeObject:cell2InSection1];
[section2 insertObject:cell2InSection1 atIndex:0];
NSIndexPath *sourceIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
NSIndexPath *destinationIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
[self.myTableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
}
@end
Карта через MapView
Файл Creating_a_Map_ViewViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface Creating_a_Map_ViewViewController : UIViewController
@property (nonatomic, strong) MKMapView *myMapView;
@end
Файл Creating_a_Map_ViewViewController.m
#import "Creating_a_Map_ViewViewController.h"
@implementation Creating_a_Map_ViewViewController
@synthesize myMapView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myMapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
/* Установить тип карты со ступтника */
self.myMapView.mapType = MKMapTypeSatellite;
self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
/* Добавить карту во View */
[self.view addSubview:self.myMapView];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myMapView = nil;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation : (UIInterfaceOrientation)interfaceOrientation{
return YES;
}
@end
Управление событиями на карте через MapView
Файл Handling_the_Events_of_a_Map_ViewViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface Handling_the_Events_of_a_Map_ViewViewController
: UIViewController <MKMapViewDelegate>
@property (nonatomic, strong) MKMapView *myMapView;
@end
Файл Handling_the_Events_of_a_Map_ViewViewController.m
#import "Handling_the_Events_of_a_Map_ViewViewController.h"
@implementation Creating_a_Map_ViewViewController
@synthesize myMapView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.myMapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
/* Установить тип карты со ступтника */
self.myMapView.mapType = MKMapTypeSatellite;
/* Установка делегата для карты */
self.myMapView.delegate = self;
self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
/* Добавить карту во View */
[self.view addSubview:self.myMapView];
}
@end
Установка на карте пометки о местоположении устройства через MapView
Файл Pinpointing_the_Location_of_a_DeviceViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface Pinpointing_the_Location_of_a_DeviceViewController
: UIViewController <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *myLocationManager;
@end
Файл Pinpointing_the_Location_of_a_DeviceViewController.m
#import "Pinpointing_the_Location_of_a_DeviceViewController.h"
@implementation Pinpointing_the_Location_of_a_DeviceViewController
@synthesize myLocationManager;
- (void)viewDidLoad {
[super viewDidLoad];
if ([CLLocationManager locationServicesEnabled]){
self.myLocationManager = [[CLLocationManager alloc] init];
self.myLocationManager.delegate = self;
self.myLocationManager.purpose = @"To provide functionality based on user's current location.";
[self.myLocationManager startUpdatingLocation];
} else {
/* Сервисы определения местоположения недоступны. Вывести на экран предложение о включении сервисов определения местоположения. */
NSLog(@"Location services are not enabled");
}
}
- (void) viewDidUnload{
[super viewDidUnload];
[self.myLocationManager stopUpdatingLocation];
self.myLocationManager = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation :(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
/* Мы получаем новое местоположение */
NSLog(@"Latitude = %f", newLocation.coordinate.latitude);
NSLog(@"Longitude = %f", newLocation.coordinate.longitude);
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
/* Невозможно получить местоположение */
}
@end
Отображение меток на карте через MapView
Файл MyAnnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface MyAnnotation : NSObject <MKAnnotation>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic, copy, readonly) NSString *subtitle;
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates title:(NSString *)paramTitle subTitle:(NSString *)paramSubTitle;
@end
Файл MyAnnotation.m
#import "MyAnnotation.h"
@implementation MyAnnotation
CLLocationCoordinate2D coordinate;
@synthesize coordinate, title, subtitle;
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates
title:(NSString *)paramTitle subTitle:(NSString *)paramSubTitle{
self = [super init];
if (self != nil){
coordinate = paramCoordinates;
title = paramTitle;
subtitle = paramSubTitle;
}
return(self);
}
@end
Файл Displaying_Pins_on_a_Map_ViewViewController.m
#import "Displaying_Pins_on_a_Map_ViewViewController.h"
#import "MyAnnotation.h"
@implementation Displaying_Pins_on_a_Map_ViewViewController
@synthesize myMapView;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
/* Очистить закэшированные данные, которые не используются, картинки и так далее. */
}
- (void)viewDidLoad {
[super viewDidLoad];
/* Создание карты по размеру области View */
self.myMapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
/* Установить делегата для карты */
self.myMapView.delegate = self;
/* Установить тип карты Standard */
self.myMapView.mapType = MKMapTypeStandard;
self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
/* Добавить карту во View */
[self.view addSubview:self.myMapView];
/* Это просто местоположение location */
CLLocationCoordinate2D location = CLLocationCoordinate2DMake(50.82191692907181, -0.13811767101287842);
/* Создание пометки, используя местоположение location */
MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinates:location title:@"My Title" subTitle:@"My Sub Title"];
/* Добавление пометки на карту */
[self.myMapView addAnnotation:annotation];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.myMapView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation
:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
@end
Отображение меток с разными цветами на карте через MapView
Файл MyAnnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
/* Это стандартный SDK pin colors. Мы устанавливаем уникальные идентификаторы цвета для каждой пометки для того, чтобы позже использовать метки, которые мы уже создали с тем же цветом. */
#define REUSABLE_PIN_RED @"Red"
#define REUSABLE_PIN_GREEN @"Green"
#define REUSABLE_PIN_PURPLE @"Purple"
@interface MyAnnotation : NSObject <MKAnnotation>
@property (nonatomic, unsafe_unretained, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, unsafe_unretained) MKPinAnnotationColor pinColor;
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates
title:(NSString*)paramTitle subTitle:(NSString*)paramSubTitle;
+ (NSString *) reusableIdentifierforPinColor : (MKPinAnnotationColor)paramColor;
@end
Файл MyAnnotation.m
#import "MyAnnotation.h"
@implementation MyAnnotation
@synthesize coordinate;
@synthesize title;
@synthesize subtitle;
@synthesize pinColor;
+ (NSString *) reusableIdentifierforPinColor :(MKPinAnnotationColor)paramColor{
NSString *result = nil;
switch (paramColor){
case MKPinAnnotationColorRed:{
result = REUSABLE_PIN_RED;
break;
}
case MKPinAnnotationColorGreen:{
result = REUSABLE_PIN_GREEN;
break;
}
case MKPinAnnotationColorPurple:{
result = REUSABLE_PIN_PURPLE;
break;
}
}
return result;
}
- (id) initWithCoordinates:(CLLocationCoordinate2D)paramCoordinates title:(NSString*)paramTitle subTitle:(NSString*)paramSubTitle{
self = [super init];
if (self != nil){
coordinate = paramCoordinates;
title = paramTitle;
subtitle = paramSubTitle;
pinColor = MKPinAnnotationColorGreen;
}
return self;
}
@end
Файл Displaying_Pins_with_Different_Colors_on_a_Map_ViewViewController.h
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface Displaying_Pins_with_Different_Colors_on_a_Map_ViewViewController
: UIViewController <MKMapViewDelegate>
@property (nonatomic, strong) MKMapView *myMapView;
@end
Файл Displaying_Pins_with_Different_Colors_on_a_Map_ViewViewController.m
#import "Displaying_Pins_with_Different_Colors_on_a_Map_ViewViewController.h"
#import "MyAnnotation.h"
@implementation Displaying_Pins_with_Different_Colors_on_a_Map_ViewViewController
@synthesize myMapView;
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
MKAnnotationView *result = nil;
if ([annotation isKindOfClass:[MyAnnotation class]] == NO){
return result;
}
if ([mapView isEqual:self.myMapView] == NO){
/* Мы хотим обработать это событие только для Map View, которую мы создали ранее */
return result;
}
/* Сперва преобразуйте пометку для MapView, для которой сработало сообщение делегата */
MyAnnotation *senderAnnotation = (MyAnnotation *)annotation;
/* Используя метод класса, который мы определили в нашем классе, мы будем получать повторно использующийся идентификатор для созданной нами метки */
NSString *pinReusableIdentifier = [MyAnnotation reusableIdentifierforPinColor:senderAnnotation.pinColor];
/* Используя идентификатор, полученный выше, мы будем повторно использовать метку на картеMap View */
MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [mapView
dequeueReusableAnnotationViewWithIdentifier:pinReusableIdentifier];
if (annotationView == nil){
/* Если мы не сможем использовать метку, тогда мы создадим её */
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:senderAnnotation reuseIdentifier:pinReusableIdentifier];
/* Убедимся, что мы можем видеть выноски на верху метки в случае, если мы добавили заголовок или подзаголовок к каждой метке */
[annotationView setCanShowCallout:YES];
}
/* Теперь убедимся, что где бы мы не использовали метку, её цвет будет совпадать с цветом пометки */
annotationView.pinColor = senderAnnotation.pinColor;
result = annotationView;
return result;
}
- (void)viewDidLoad {
[super viewDidLoad];
/* Создание карты размером с наш View */
self.myMapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
self.myMapView.delegate = self;
/* Установить тип карты Standard */
self.myMapView.mapType = MKMapTypeStandard;
self.myMapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
/* Добавить карту во View */
[self.view addSubview:self.myMapView];
/* Это просто координаты метстоположения location */
CLLocationCoordinate2D location;
location.latitude = 50.82191692907181;
location.longitude = -0.13811767101287842;
/* Создать пометку, используя координаты метоположения location */
MyAnnotation *annotation = [[MyAnnotation alloc] initWithCoordinates:location title:@"My Title" subTitle:@"My Sub Title"];
annotation.pinColor = MKPinAnnotationColorPurple;
/* Добавить метку на карту */
[self.myMapView addAnnotation:annotation];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myMapView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation
:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
@end
Отображение собственных меток на карте через MapView
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation{
MKAnnotationView *result = nil;
if ([annotation isKindOfClass:[MyAnnotation class]] == NO){
return result;
}
if ([mapView isEqual:self.myMapView] == NO){
/* Мы хотим обработать это событие только для Map View, которую мы создали ранее */
return result;
}
/* Сперва мы изменим тип пометки для Map View, на котрой сработало событие делегата */
MyAnnotation *senderAnnotation = (MyAnnotation *)annotation;
/* Используя метод класса, который мы определили в нашем классе для пометок, мы получи повторно используемый идентификатор для метки, которую мы создалт */
NSString *pinReusableIdentifier = [MyAnnotation reusableIdentifierforPinColor:senderAnnotation.pinColor];
/* Используем идентификатор, который мы получили выше для повторно используемой метки на карте Map View */
MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [mapView dequeueReusableAnnotationViewWithIdentifier: pinReusableIdentifier];
if (annotationView == nil){
/* Если мы не сможем использовать метку, тогда мы создадим её */
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:senderAnnotation reuseIdentifier:pinReusableIdentifier];
/* Убудимся, что мы можем видеть выноски на верху каждой метки в случае присвоения заголовка и подзаголовка для каждой метки */
annotationView.canShowCallout = YES;
}
/* Теперь убедимся, что цвет метки будет совпадать с цветом пометки */
annotationView.pinColor = senderAnnotation.pinColor;
UIImage *pinImage = [UIImage imageNamed:@"BluePin.png"];
if (pinImage != nil){
annotationView.image = pinImage;
}
result = annotationView;
return result;
}
Конвертирование координат в адрес места через MapView
Файл Converting_Longitude_and_Latitude_to_a_Meaningful_AddressViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface
Converting_Longitude_and_Latitude_to_a_Meaningful_AddressViewController
: UIViewController
@property (nonatomic, strong) CLGeocoder *myGeocoder;
@end
Файл Converting_Longitude_and_Latitude_to_a_Meaningful_AddressViewController.m
@implementation
Converting_Longitude_and_Latitude_to_a_Meaningful_AddressViewController
@synthesize myGeocoder;
- (void)viewDidLoad{
[super viewDidLoad];
CLLocation *location = [[CLLocation alloc] initWithLatitude:+38.4112810
longitude:-122.8409780f];
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil &&[placemarks count] > 0){
CLPlacemark *placemark = [placemarks objectAtIndex:0];
/* Мы получили результаты: */
NSLog(@"Country = %@", placemark.country);
NSLog(@"Postal Code = %@", placemark.postalCode);
NSLog(@"Locality = %@", placemark.locality);
} else if (error == nil &&[placemarks count] == 0){
NSLog(@"No results were returned.");
} else if (error != nil){
NSLog(@"An error occurred = %@", error);
}
}];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myGeocoder = nil;
}
@end
Результат вывода NSLog:
Country = United States
Postal Code = 95472
Locality = Sebastopol
Конвертирование адреса места в координаты через MapView
Файл Converting_Meaningful_Addresses_to_Longitude_and_LatitudeViewController.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface
Converting_Meaningful_Addresses_to_Longitude_and_LatitudeViewController
: UIViewController
@property (nonatomic, strong) CLGeocoder *myGeocoder;
@end
Файл Converting_Meaningful_Addresses_to_Longitude_and_LatitudeViewController.m
@implementation
Converting_Meaningful_Addresses_to_Longitude_and_LatitudeViewController
@synthesize myGeocoder;
- (void)viewDidLoad{
[super viewDidLoad];
/* У нас есть наш адрес */
NSString *oreillyAddress = @"1005 Gravenstein Highway North, Sebastopol, CA 95472, USA";
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0 && error == nil){
NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
} else if ([placemarks count] == 0 && error == nil){
NSLog(@"Found no placemarks.");
} else if (error != nil){
NSLog(@"An error occurred = %@", error);
}
}];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.myGeocoder = nil;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
/* Очистить закэшированные данные, такие как картинки, которые больше не используются */
}
@end
Результат вывода NSLog:
Found 1 placemark(s).
Longitude = -122.841135
Latitude = 38.410373
Типы взаимодействий с iPhone, iPad и iPod
Swipe
Rotation
Pinch
Pan
Long press
Tap
Обнаружение Swipe движений
- (void)viewDidLoad {
[super viewDidLoad];
/* Инициализировать объект распознавания Swipe */
self.swipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipes:)];
/* Обнаружение Swipes выполненных справа налево */
self.swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
/* Нужен только 1 палец*/
self.swipeGestureRecognizer.numberOfTouchesRequired = 1;
/* Добавить объект распознавания Swipes к View */
[self.view addGestureRecognizer:self.swipeGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.swipeGestureRecognizer = nil;
}
- (void) handleSwipes:(UISwipeGestureRecognizer *)paramSender{
if (paramSender.direction & UISwipeGestureRecognizerDirectionDown){
NSLog(@"Swiped Down.");
}
if (paramSender.direction & UISwipeGestureRecognizerDirectionLeft){
NSLog(@"Swiped Left.");
}
if (paramSender.direction & UISwipeGestureRecognizerDirectionRight){
NSLog(@"Swiped Right.");
}
if (paramSender.direction & UISwipeGestureRecognizerDirectionUp){
NSLog(@"Swiped Up.");
}
}
Обнаружение вращения устройства через Rotation
Файл Detecting_Rotation_GesturesViewController.h
#import <UIKit/UIKit.h>
@interface Detecting_Rotation_GesturesViewController : UIViewController
@property (nonatomic, strong) UIRotationGestureRecognizer *rotationGestureRecognizer;
@property (nonatomic, strong) UILabel *helloWorldLabel;
@property (nonatomic, unsafe_unretained) CGFloat rotationAngleInRadians;
@end
Файл Detecting_Rotation_GesturesViewController.m
#import "Detecting_Rotation_GesturesViewController.h"
@implementation Detecting_Rotation_GesturesViewController
@synthesize rotationGestureRecognizer;
@synthesize helloWorldLabel;
@synthesize rotationAngleInRadians;
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.helloWorldLabel = [[UILabel alloc] initWithFrame:CGRectZero];
self.helloWorldLabel.text = @"Hello, World!";
self.helloWorldLabel.font = [UIFont systemFontOfSize:16.0f];
[self.helloWorldLabel sizeToFit];
self.helloWorldLabel.center = self.view.center;
[self.view addSubview:self.helloWorldLabel];
self.rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotations:)];
[self.view addGestureRecognizer:self.rotationGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.helloWorldLabel = nil;
self.rotationGestureRecognizer = nil;
}
- (void) handleRotations:(UIRotationGestureRecognizer *)paramSender{
if (self.helloWorldLabel == nil){
return;
}
/* Взять предыдущее rotation и добавить текущее rotation в него */
self.helloWorldLabel.transform = CGAffineTransformMakeRotation(self.rotationAngleInRadians + paramSender.rotation);
/* В конце поворота сохранить угол для дальнейшего использования */
if (paramSender.state == UIGestureRecognizerStateEnded){
self.rotationAngleInRadians += paramSender.rotation;
}
}
@end
Обнаружение движений Panning и Dragging
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/* Сначала создадим метку label */
CGRect labelFrame = CGRectMake(0.0f, /* X */
0.0f, /* Y */
150.0f, /* Ширина */
100.0f); /* Высота */
self.helloWorldLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.helloWorldLabel.text = @"Hello World";
self.helloWorldLabel.backgroundColor = [UIColor blackColor];
self.helloWorldLabel.textColor = [UIColor whiteColor];
self.helloWorldLabel.textAlignment = UITextAlignmentCenter;
/* Убедимся, что включены взаимодействия с пользователем, в противном случае прикосновения не будут обрабатываться меткой label */
self.helloWorldLabel.userInteractionEnabled = YES;
/* А теперь убедимся, что метка отображается на нашемView */
[self.view addSubview:self.helloWorldLabel];
/* Создадим Pan Gesture Recognizer */
self.panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGestures:)];
/* Необходимо, чтобы определялись прикосновения только от одного пальца */
self.panGestureRecognizer.minimumNumberOfTouches = 1;
self.panGestureRecognizer.maximumNumberOfTouches = 1;
/* Добавляем распознаватель прикосновений в наш View */
[self.helloWorldLabel addGestureRecognizer:self.panGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.panGestureRecognizer = nil;
self.helloWorldLabel = nil;
}
- (void) handlePanGestures:(UIPanGestureRecognizer*)paramSender{
if (paramSender.state != UIGestureRecognizerStateEnded && paramSender.state != UIGestureRecognizerStateFailed){
CGPoint location = [paramSender locationInView:paramSender.view.superview];
paramSender.view.center = location;
}
}
Обнаружение длительных прикосновений к экрану Long Press
Файл Detecting_Long_Press_GesturesViewController.h
#import <UIKit/UIKit.h>
@interface Detecting_Long_Press_GesturesViewController : UIViewController
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) UIButton *dummyButton;
@end
Файл Detecting_Long_Press_GesturesViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.dummyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.dummyButton.frame = CGRectMake(0.0f,
0.0f,
72.0f,
37.0f);
self.dummyButton.center = self.view.center;
[self.view addSubview:self.dummyButton];
/* Сперва создадим gesture recognizer */
self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
/* Число пальцев, которые должны прикасаться к экрану */
self.longPressGestureRecognizer.numberOfTouchesRequired = 2;
/* Максиму 100 пикселей движения допустимо перед распознаванием прикосновения */
self.longPressGestureRecognizer.allowableMovement = 100.0f;
/* Пользователь должен прикоснуться двумя пальцами к экрану (numberOfTouchesRequired) по крайней мере на 1 секунду для распознавания прикосновения */
self.longPressGestureRecognizer.minimumPressDuration = 1.0;
/* Добавлени gesture recognizer к View */
[self.view addGestureRecognizer:self.longPressGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.longPressGestureRecognizer = nil;
self.dummyButton = nil;
}
- (void) handleLongPressGestures:(UILongPressGestureRecognizer *)paramSender{
/* Здесь мы хотим найти среднюю точку между двумя пальцами, которыми было вызвано событие long press gesture. Мы сконфигурировали число, используя свойство numberOfTouchesRequired объекта UILongPressGestureRecognizer , который инициализировали в методе viewDidLoad контроллера View Controller. Если мы определим другое long press gesture, использующее тот же метода, то мы проигнорируем его */
if ([paramSender isEqual:self.longPressGestureRecognizer]){
if (paramSender.numberOfTouchesRequired == 2){
CGPoint touchPoint1 = [paramSender locationOfTouch:0 inView:paramSender.view];
CGPoint touchPoint2 = [paramSender locationOfTouch:1 inView:paramSender.view];
CGFloat midPointX = (touchPoint1.x + touchPoint2.x) / 2.0f;
CGFloat midPointY = (touchPoint1.y + touchPoint2.y) / 2.0f;
CGPoint midPoint = CGPointMake(midPointX, midPointY);
self.dummyButton.center = midPoint;
} else {
/* Это long press gesture recognizer с более чем 2-мя пальцами */
}
}
}
Обнаружение нажтий Tap
Файл Detecting_Tap_GesturesViewController.h
#import <UIKit/UIKit.h>
@interface Detecting_Tap_GesturesViewController : UIViewController
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;
@end
Файл Detecting_Tap_GesturesViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
/* Создаем Tap Gesture Recognizer */
self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTaps:)];
/* Указываем число пальцев, которые должны прикоснуться к экрану */
self.tapGestureRecognizer.numberOfTouchesRequired = 2;
/* Указываем число прикосновений, которые должны быть выполнены для распознавания */
self.tapGestureRecognizer.numberOfTapsRequired = 3;
/* Добавляем gesture recognizer к View */
[self.view addGestureRecognizer:self.tapGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.tapGestureRecognizer = nil;
}
- (void) handleTaps:(UITapGestureRecognizer*)paramSender{
NSUInteger touchCounter = 0;
for (touchCounter = 0;
touchCounter < paramSender.numberOfTouchesRequired;
touchCounter++){
CGPoint touchPoint = [paramSender locationOfTouch:touchCounter inView:paramSender.view];
NSLog(@"Touch #%lu: %@", (unsigned long)touchCounter+1, NSStringFromCGPoint(touchPoint));
}
}
В консоли NSLog выведет следующий результат:
Touch #1: {107, 186}
Touch #2: {213, 254}
Обнаружение щипков экрана Pinch
Файл Detecting_Pinch_GesturesViewController.h
#import <UIKit/UIKit.h>
@interface Detecting_Pinch_GesturesViewController : UIViewController
@property (nonatomic, strong) UIPinchGestureRecognizer *pinchGestureRecognizer;
@property (nonatomic, strong) UILabel *myBlackLabel;
@property (nonatomic, unsafe_unretained) CGFloat currentScale;
@end
Файл Detecting_Pinch_GesturesViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
CGRect labelRect = CGRectMake(0.0f, /* X */
0.0f, /* Y */
200.0f, /* Ширина */
200.0f); /* Высота */
self.myBlackLabel = [[UILabel alloc] initWithFrame:labelRect];
self.myBlackLabel.center = self.view.center;
self.myBlackLabel.backgroundColor = [UIColor blackColor];
/* Без этого наш pinch gesture recognizer не будет работать */
self.myBlackLabel.userInteractionEnabled = YES;
[self.view addSubview:self.myBlackLabel];
/* Создаем Pinch Gesture Recognizer */
self.pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinches:)];
/* Добавляем gesture recognizer к View */
[self.myBlackLabel addGestureRecognizer:self.pinchGestureRecognizer];
}
- (void) viewDidUnload{
[super viewDidUnload];
self.myBlackLabel = nil;
self.pinchGestureRecognizer = nil;
}
- (void) handlePinches:(UIPinchGestureRecognizer*)paramSender{
if (paramSender.state == UIGestureRecognizerStateEnded){
self.currentScale = paramSender.scale;
} else if (paramSender.state == UIGestureRecognizerStateBegan && self.currentScale != 0.0f){
paramSender.scale = self.currentScale;
}
if (paramSender.scale != NAN && paramSender.scale != 0.0){
paramSender.view.transform = CGAffineTransformMakeScale(paramSender.scale, paramSender.scale);
}
}
Получение HTML-кода интернет страницы
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
/* Получение папки с документами */
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,
YES) objectAtIndex:0];
/* Добавление имени файла в папку с документами */
NSString *filePath = [documentsDir stringByAppendingPathComponent:@"apple.html"];
/* Запись данных в файл */
[data writeToFile:filePath atomically:YES];
NSLog(@"Successfully saved the file to %@", filePath);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Управления таймаутами при асинхронных запросах
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0f];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Синхронная загрузка содержимого вместе с NSURLConnection
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSLog(@"We are here...");
NSString *urlAsString = @"http://www.yahoo.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSLog(@"Firing synchronous url connection...");
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if ([data length] > 0 && error == nil){
NSLog(@"%lu bytes of data was returned.", (unsigned long)[data length]);
} else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
NSLog(@"We are done.");
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
В консоль будет выведен следующий результат через NSLog:
We are here...
Firing synchronous url connection...
194472 bytes of data was returned.
We are done.
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSLog(@"We are here...");
NSString *urlAsString = @"http://www.yahoo.com";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if ([data length] > 0 && error == nil){
NSLog(@"%lu bytes of data was returned.", (unsigned long)[data length]);
} else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
});
NSLog(@"We are done.");
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
В консоль будет выведен следующий результат через NSLog:
We are here...
Firing synchronous url connection...
We are done.
194326 bytes of data was returned.
Изменение URL Request через NSMutableURLRequest
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest new];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setURL:url];
Посылка HTTP GET Requests через NSURLConnection
/* URL = http://pixolity.com/get.php?param1=First¶m2=Second */
NSString *urlAsString = @"http://pixolity.com/get.php";
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Результат вывода в косоль через NSLog:
HTML =
<html>
<head>
<title>iOS 5 Programming Cookbook GET Example</title>
</head>
<body>
<b>HTTP Method</b> = GET<br/><br/><b>Query String</b> = Array
(
[param1] => First
[param2] => Second
)
</body>
</html>
Посылка HTTP POST Requests через NSURLConnection
NSString *urlAsString = @"http://pixolity.com/post.php";
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"POST"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Результат вывода в косоль через NSLog:
HTML =
<html>
<head>
<title>iOS 5 Programming Cookbook POST Example</title>
</head>
<body>
<b>HTTP Method</b> = POST<br/><br/><b>Query String</b> = Array
(
[param1] => First
[param2] => Second
)
<br/><br/><b>Body Parameters</b> = Array
(
[bodyParam1] => BodyValue1
[bodyParam2] => BodyValue2
)
</body>
</html>
Посылка HTTP DELETE Requests через NSURLConnection
NSString *urlAsString = @"http://pixolity.com/delete.php";
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"DELETE"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
} else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
} else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Результат вывода в консоль через NSLog:
HTML =
<html>
<head>
<title>iOS 5 Programming Cookbook DELETE Example</title>
</head>
<body>
<b>HTTP Method</b> = DELETE<br/><br/><b>Query String</b> = Array
(
[param1] => First
[param2] => Second
)
<br/><br/><b>Body Parameters</b> = Array
(
[bodyParam1] => BodyValue1
[bodyParam2] => BodyValue2
)
</body>
</html>
Посылка HTTP PUT Requests через NSURLConnection
NSString *urlAsString = @"http://pixolity.com/put.php";
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"PUT"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html);
}else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
}else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
Результат вывода в консоль через NSLog:
HTML =
<html>
<head>
<title>iOS 5 Programming Cookbook PUT Example</title>
</head>
<body>
<b>HTTP Method</b> = PUT<br/><br/><b>Query String</b> = Array
(
[param1] => First
[param2] => Second
)
<br/><br/><b>Body Parameters</b> = Array
(
[bodyParam1] => BodyValue1
[bodyParam2] => BodyValue2
)
</body>
</html>
Преобразование массивов и хэш-массивов в JSON-формат
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Anthony" forKey:@"First Name"];
[dictionary setValue:@"Robbins" forKey:@"Last Name"];
[dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];
NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:
@"Anthony's Son 1",
@"Anthony's Daughter 1",
@"Anthony's Son 2",
@"Anthony's Son 3",
@"Anthony's Daughter 2",
nil];
[dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] > 0 && error == nil){
NSLog(@"Successfully serialized the dictionary into data = %@", jsonData);
}else if ([jsonData length] == 0 && error == nil){
NSLog(@"No data was returned after serialization.");
} else if (error != nil){
NSLog(@"An error happened = %@", error);
}
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Anthony" forKey:@"First Name"];
[dictionary setValue:@"Robbins" forKey:@"Last Name"];
[dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];
NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:
@"Anthony's Son 1",
@"Anthony's Daughter 1",
@"Anthony's Son 2",
@"Anthony's Son 3",
@"Anthony's Daughter 2",
nil];
[dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] > 0 && error == nil){
NSLog(@"Successfully serialized the dictionary into data.");
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON String = %@", jsonString);
} else if ([jsonData length] == 0 && error == nil){
NSLog(@"No data was returned after serialization.");
} else if (error != nil){
NSLog(@"An error happened = %@", error);
}
Рузультат преобразования хэш-массива в формат JSON:
JSON String = {
"Last Name" : "Robbins",
"First Name" : "Anthony",
"children" : [
"Anthony's Son 1",
"Anthony's Daughter 1",
"Anthony's Son 2",
"Anthony's Son 3",
"Anthony's Daughter 2"
],
"Age" : 51
}
Преобразование данных в формате JSON в массивы и хэш-массивы
error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject != nil && error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);
} else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Dersialized JSON Array = %@", deserializedArray);
} else {
/* Будут возвращены другие объекты. Мы не значем что делать в этой ситуации, так как deserializer может возвращать только массивы и хэш-массивы */
}
} else if (error != nil){
NSLog(@"An error happened while deserializing the JSON data.");
}
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:@"Anthony" forKey:@"First Name"];
[dictionary setValue:@"Robbins" forKey:@"Last Name"];
[dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];
NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:
@"Anthony's Son 1",
@"Anthony's Daughter 1",
@"Anthony's Son 2",
@"Anthony's Son 3",
@"Anthony's Daughter 2",
nil];
[dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] > 0 && error == nil){
NSLog(@"Successfully serialized the dictionary into data.");
/* Теперь попробуем преобразовать объект JSON в хэш-массив */
error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject != nil && error == nil){
NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);
} else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Dersialized JSON Array = %@", deserializedArray);
} else {
/* Будут возвращены другие объекты. Мы не значем что делать в этой ситуации, так как deserializer может возвращать только массивы и хэш-массивы */
}
} else if (error != nil){
NSLog(@"An error happened while deserializing the JSON data.");
}
} else if ([jsonData length] == 0 && error == nil){
NSLog(@"No data was returned after serialization.");
} else if (error != nil){
NSLog(@"An error happened = %@", error);
}
Интеграция функционала Twitter в приложение
Файл Integrating_Twitter_Functionality_Into_Your_AppsViewController.h
#import <UIKit/UIKit.h>
#import <Twitter/Twitter.h>
@interface Integrating_Twitter_Functionality_Into_Your_AppsViewController
: UIViewController
@property (nonatomic, strong) TWTweetComposeViewController *twitterController;
@end
Файл Integrating_Twitter_Functionality_Into_Your_AppsViewController.m
#import "Integrating_Twitter_Functionality_Into_Your_AppsViewController.h"
@implementation
Integrating_Twitter_Functionality_Into_Your_AppsViewController
@synthesize twitterController;
- (void)viewDidLoad{
[super viewDidLoad];
self.twitterController = [[TWTweetComposeViewController alloc] init];
[self.twitterController setInitialText:@"Your Tweet Goes Here"];
[self.navigationController presentModalViewController:self.twitterController
animated:YES];
}
@end
- (void)viewDidLoad{
[super viewDidLoad];
self.twitterController = [[TWTweetComposeViewController alloc] init];
NSString *text = @"Anthony Robbins at Unleash the Power Within (UPW) in London";
[self.twitterController setInitialText:text];
UIImage *anthonyRobbins = [UIImage imageNamed:@"Anthony Robbins.jpg"];
[self.twitterController addImage:anthonyRobbins];
NSURL *url = [NSURL URLWithString:@"http://www.tonyrobbins.com"];
[self.twitterController addURL:url];
[self.navigationController presentModalViewController:self.twitterController
animated:YES];
}
- (void)viewDidLoad{
[super viewDidLoad];
self.twitterController = [[TWTweetComposeViewController alloc] init];
__weak Integrating_Twitter_Functionality_Into_Your_AppsViewController *weakSelf = self;
[self.twitterController setCompletionHandler: ^(TWTweetComposeViewControllerResult result){
Integrating_Twitter_Functionality_Into_Your_AppsViewController *strongSelf = weakSelf;
switch (result){
case TWTweetComposeViewControllerResultDone:{
/* Tweet успешно отправлен.
Will be dismissed automatically */
break;
}
case TWTweetComposeViewControllerResultCancelled:{
if (strongSelf != nil){
[strongSelf.twitterController dismissModalViewControllerAnimated:YES];
}
break;
}
}
}];
NSString *text = @"Anthony Robbins at Unleash the Power Within (UPW) in London";
[self.twitterController setInitialText:text];
UIImage *anthonyRobbins = [UIImage imageNamed:@"Anthony Robbins.jpg"];
[self.twitterController addImage:anthonyRobbins];
NSURL *url = [NSURL URLWithString:@"http://www.tonyrobbins.com"];
[self.twitterController addURL:url];
[self.navigationController presentModalViewController:self.twitterController
animated:YES];
}
Парсинг XML через NSXMLParser
<?xml version="1.0" encoding="UTF-8"?>
<root>
<person id="1">
<firstName>Anthony</firstName>
<lastName>Robbins</lastName>
<age>51</age>
</person>
<person id="2">
<firstName>Richard</firstName>
<lastName>Branson</lastName>
<age>61</age>
</person>
</root>
Файл Parsing_XML_with_NSXMLParserAppDelegate.h
#import <UIKit/UIKit.h>
@interface Parsing_XML_with_NSXMLParserAppDelegate
: UIResponder <UIApplicationDelegate, NSXMLParserDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) NSXMLParser *xmlParser;
@end
Файл Parsing_XML_with_NSXMLParserAppDelegate.m
#import "Parsing_XML_with_NSXMLParserAppDelegate.h"
@implementation Parsing_XML_with_NSXMLParserAppDelegate
@synthesize window = _window;
@synthesize xmlParser;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"MyXML" ofType:@"xml"];
NSData *xml = [[NSData alloc] initWithContentsOfFile:xmlFilePath];
self.xmlParser = [[NSXMLParser alloc] initWithData:xml];
self.xmlParser.delegate = self;
if ([self.xmlParser parse]){
NSLog(@"The XML is parsed.");
} else{
NSLog(@"Failed to parse the XML");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
@end
Проигрывание Аудио-файлов
Файл Playing_Audio_FilesViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface Playing_Audio_FilesViewController
: UIViewController <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end
Файл Playing_Audio_FilesViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
/* Запустить audio player */
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
error:&error];
/* Мы получили instance AVAudioPlayer? */
if (self.audioPlayer != nil){
/* Установка делегата и начало проигрывания */
self.audioPlayer.delegate = self;
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
/* Проигрывание успешно начато */
} else {
/* Проигрывание не получилось */
}
} else {
/* Не получилось instantiate AVAudioPlayer */
}
});
}
Управление прерыванием проигрывания Аудио-файла
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Сессия проигрывания прервалась. Плеер поставлен на паузу здесь.*/
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionFlags_ShouldResume && player != nil){
[player play];
}
}
Запись Аудио
Файл Recording_AudioViewController.h
#import <UIKit/UIKit.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AVFoundation/AVFoundation.h>
@interface Recording_AudioViewController : UIViewController
<AVAudioPlayerDelegate, AVAudioRecorderDelegate>
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
- (NSString *) audioRecordingPath;
- (NSDictionary *) audioRecordingSettings;
@end
Файл Recording_AudioViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error = nil;
NSString *pathAsString = [self audioRecordingPath];
NSURL *audioRecordingURL = [NSURL fileURLWithPath:pathAsString];
self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioRecordingURL settings:[self audioRecordingSettings] error:&error];
if (self.audioRecorder != nil){
self.audioRecorder.delegate = self;
/* Подготовка recorder и щатем старт записи звука */
if ([self.audioRecorder prepareToRecord] && [self.audioRecorder record]){
NSLog(@"Successfully started to record.");
/* Через 5 секунд остановим процесс записи */
[self performSelector:@selector(stopRecordingOnAudioRecorder:) withObject:self.audioRecorder afterDelay:5.0f];
} else {
NSLog(@"Failed to record.");
self.audioRecorder = nil;
}
} else {
NSLog(@"Failed to create an instance of the audio recorder.");
}
}
- (void) viewDidUnload{
[super viewDidUnload];
if ([self.audioRecorder isRecording]){
[self.audioRecorder stop];
}
self.audioRecorder = nil;
if ([self.audioPlayer isPlaying]){
[self.audioPlayer stop];
}
self.audioPlayer = nil;
}
- (NSString *) audioRecordingPath{
NSString *result = nil;
NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsFolder = [folders objectAtIndex:0];
result = [documentsFolder stringByAppendingPathComponent:@"Recording.m4a"];
return result;
}
- (NSDictionary *) audioRecordingSettings{
NSDictionary *result = nil;
/* Подготовим опции audio recorder options в хэш-массиве. Позже мы будем использовать этот массив для создания audio
recorder с типом AVAudioRecorder */
NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];
[settings setValue:[NSNumber numberWithInteger:kAudioFormatAppleLossless] forKey:AVFormatIDKey];
[settings setValue:[NSNumber numberWithFloat:44100.0f] forKey:AVSampleRateKey];
[settings setValue:[NSNumber numberWithInteger:1] forKey:AVNumberOfChannelsKey];
[settings setValue:[NSNumber numberWithInteger:AVAudioQualityLow] forKey:AVEncoderAudioQualityKey];
result = [NSDictionary dictionaryWithDictionary:settings];
return result;
}
- (void) stopRecordingOnAudioRecorder :(AVAudioRecorder *)paramRecorder{
/* Просто остановим audio recorder здесь */
[paramRecorder stop];
}
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
if (flag){
NSLog(@"Successfully stopped the audio recording process.");
/* Попробуем получить данные из записанного файла */
NSError *playbackError = nil;
NSError *readingError = nil;
NSData *fileData = [NSData dataWithContentsOfFile:[self audioRecordingPath] options:NSDataReadingMapped error:&readingError];
/* Сформируем audio player и заставим его проигрывать данные из записанного файла */
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&playbackError];
/* Можем ли мы создать аудио плеер? */
if (self.audioPlayer != nil){
self.audioPlayer.delegate = self;
/* Приготовимся к проигрыванию и начнем проигрывать запись */
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Started playing the recorded audio.");
} else {
NSLog(@"Could not play the audio.");
}
} else {
NSLog(@"Failed to create an audio player.");
}
} else {
NSLog(@"Stopping the audio recording failed.");
}
/* Здесь нам больше не нужен audio recorder */
self.audioRecorder = nil;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
if (flag){
NSLog(@"Audio player stopped correctly.");
} else {
NSLog(@"Audio player did not stop correctly.");
}
if ([player isEqual:self.audioPlayer]){
self.audioPlayer = nil;
} else {
/* Это не наш плеер */
}
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Audio session была деактивирована здесь */
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionFlags_ShouldResume){
[player play];
}
}
Управление прерыванием записи Аудио
- (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{
NSLog(@"Recording process is interrupted");
}
- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withFlags:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionFlags_ShouldResume){
NSLog(@"Resuming the recording...");
[recorder record];
}
}
Проигрывание Аудио поверх других активных звуков
Файл Playing_Audio_over_Other_Active_SoundsViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface Playing_Audio_over_Other_Active_SoundsViewController
: UIViewController <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end
Файл Playing_Audio_over_Other_Active_SoundsViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryAmbient error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *audioPlayerError = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&audioPlayerError];
if (self.audioPlayer != nil){
self.audioPlayer.delegate = self;
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing.");
} else {
NSLog(@"Failed to play the audio file.");
self.audioPlayer = nil;
}
} else {
NSLog(@"Could not instantiate the audio player.");
}
});
}
- (void) viewDidUnload{
[super viewDidUnload];
if ([self.audioPlayer isPlaying]){
[self.audioPlayer stop];
}
self.audioPlayer = nil;
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Audio session будет деактивирована здесь */
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withFlags:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionFlags_ShouldResume){
[player play];
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
if (flag){
NSLog(@"Audio player stopped correctly.");
} else {
NSLog(@"Audio player did not stop correctly.");
}
if ([player isEqual:self.audioPlayer]){
self.audioPlayer = nil;
} else {
/* Это не наш audio player */
}
}
Проигрывание Видео-файлов
Файл Playing_Video_FilesViewController.h
#import <UIKit/UIKit.h>
#import <MediaPlayer/MediaPlayer.h>
@interface Playing_Video_FilesViewController : UIViewController
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
@property (nonatomic, strong) UIButton *playButton;
@end
Файл Playing_Video_FilesViewController.m
- (void) startPlayingVideo:(id)paramSender{
/* Сперва сконструируем URL файлав нашем application bundle, который нужен для проигрывания в movie player */
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *urlAsString = [mainBundle pathForResource:@"Sample"
ofType:@"m4v"];
NSURL *url = [NSURL fileURLWithPath:urlAsString];
/* Если мы уже создали movie player ранее, то отстановим его */
if (self.moviePlayer != nil){
[self stopPlayingVideo:nil];
}
/* Теперь создадим новый видеоплеер, используя URL */
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
if (self.moviePlayer != nil){
/* Прослушиваем уведомления, которые посылает movie player, когда он завершает проигрывание файла */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishedPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
NSLog(@"Successfully instantiated the movie player.");
/* Масштабируем movie player to fit the aspect ratio */
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
/* Начнем проигрывание video в полноэкранном режиме */
[self.moviePlayer play];
[self.view addSubview:self.moviePlayer.view];
[self.moviePlayer setFullscreen: YESanimated:YES];
} else {
NSLog(@"Failed to instantiate the movie player.");
}
}
- (void) stopPlayingVideo:(id)paramSender {
if (self.moviePlayer != nil){
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
[self.moviePlayer stop];
if ([self.moviePlayer.view.superview isEqual:self.view]){
[self.moviePlayer.view removeFromSuperview];
}
}
}
- (void) viewDidUnload{
self.playButton = nil;
[self stopPlayingVideo:nil];
self.moviePlayer = nil;
[super viewDidUnload];
}
- (void) videoHasFinishedPlaying:(NSNotification *)paramNotification{
/* Определяем причину, по которой было остановлено проигрывание видео */
NSNumber *reason = [paramNotification.userInfo valueForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
if (reason != nil){
NSInteger reasonAsInteger = [reason integerValue];
switch (reasonAsInteger){
case MPMovieFinishReasonPlaybackEnded:{
/* Проигрывание завергено нормально */
break;
}
case MPMovieFinishReasonPlaybackError:{
/* Проигрывание остановлено из-за возникшей ошибки */
break;
}
case MPMovieFinishReasonUserExited:{
/* Пользователь вышел из плеера */
break;
}
}
NSLog(@"Finish Reason = %ld", (long)reasonAsInteger);
[self stopPlayingVideo:nil];
} /* if (reason != nil){ */
}
Захват Thumbnails из Видео-файла
- (void) startPlayingVideo:(id)paramSender{
/* Сперва сконструируем URL файлав нашем application bundle, который нужен для проигрывания в movie player */
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *urlAsString = [mainBundle pathForResource:@"Sample" ofType:@"m4v"];
NSURL *url = [NSURL fileURLWithPath:urlAsString];
/* Если мы уже создали movie player ранее, то отстановим его */
if (self.moviePlayer != nil){
[self stopPlayingVideo:nil];
}
/* Теперь создадим новый видеоплеер, используя URL */
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
if (self.moviePlayer != nil){
/* Прослушиваем уведомления, которые посылает movie player, когда он завершает проигрывание файла */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoHasFinishedPlaying:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoThumbnailIsAvailable:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];
NSLog(@"Successfully instantiated the movie player.");
/* Масштабируем movie player to fit the aspect ratio */
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
/* Начнем проигрывание video в полноэкранном режиме */
[self.moviePlayer play];
[self.view addSubview:self.moviePlayer.view];
[self.moviePlayer setFullscreen:YES animated:YES];
/* Захватим кадр из 3 секунды в плеере */
NSNumber *thirdSecondThumbnail = [NSNumber numberWithFloat:3.0f];
/* Мы можем захватить столько кадров из видео сколько нам нужно. Но сейчас мы захватываем только 1 кадр. */
NSArray *requestedThumbnails = [NSArray arrayWithObject:thirdSecondThumbnail];
/* Просим movie player tзахватить кадр для нас */
[self.moviePlayer requestThumbnailImagesAtTimes:requestedThumbnails timeOption:MPMovieTimeOptionExact];
} else {
NSLog(@"Failed to instantiate the movie player.");
}
}
- (void) videoThumbnailIsAvailable:(NSNotification *)paramNotification{
MPMoviePlayerController *controller = [paramNotification object];
if (controller != nil && [controller isEqual:self.moviePlayer]){
NSLog(@"Thumbnail is available");
/* Получаем thumbnail из хэш-массива user info */
UIImage *thumbnail = [paramNotification.userInfo objectForKey:MPMoviePlayerThumbnailImageKey];
if (thumbnail != nil){
/* Мы получили картинку thumbnail. Вы можете использовать её здесь */
}
}
}
- (void) stopPlayingVideo:(id)paramSender {
if (self.moviePlayer != nil){
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];
[self.moviePlayer stop];
if ([self.moviePlayer.view.superview isEqual:self.view]){
[self.moviePlayer.view removeFromSuperview];
}
}
}
Доступ к музыкальной библиотеке Music Library
Файл Accessing_the_Music_LibraryViewController.h
@interface Accessing_the_Music_LibraryViewController : UIViewController
<MPMediaPickerControllerDelegate, AVAudioPlayerDelegate>
@property (nonatomic, strong) MPMusicPlayerController *myMusicPlayer;
@property (nonatomic, strong) UIButton *buttonPickAndPlay;
@property (nonatomic, strong) UIButton *buttonStopPlaying;
@end
Файл Accessing_the_Music_LibraryViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.buttonPickAndPlay = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.buttonPickAndPlay.frame = CGRectMake(0.0f,
0.0f,
200,
37.0f);
self.buttonPickAndPlay.center = CGPointMake(self.view.center.x, self.view.center.y - 50);
[self.buttonPickAndPlay setTitle:@"Pick and Play" forState:UIControlStateNormal];
[self.buttonPickAndPlay addTarget:self action:@selector(displayMediaPickerAndPlayItem)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttonPickAndPlay];
self.buttonStopPlaying = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.buttonStopPlaying.frame = CGRectMake(0.0f,
0.0f,
200,
37.0f);
self.buttonStopPlaying.center = CGPointMake(self.view.center.x, self.view.center.y + 50);
[self.buttonStopPlaying setTitle:@"Stop Playing" forState:UIControlStateNormal];
[self.buttonStopPlaying addTarget:self action:@selector(stopPlayingAudio) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.buttonStopPlaying];
[self.navigationController setNavigationBarHidden:YES animated:NO];
}
- (void) viewDidUnload{
[super viewDidUnload];
[self stopPlayingAudio];
self.myMusicPlayer = nil;
}
- (void) displayMediaPickerAndPlayItem{
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
if (mediaPicker != nil){
NSLog(@"Successfully instantiated a media picker.");
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = YES;
[self.navigationController presentModalViewController:mediaPicker animated:YES];
} else {
NSLog(@"Could not instantiate a media picker.");
}
}
- (void) mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
NSLog(@"Media Picker returned");
/* Сперва, если мы уже имеем созданный музыкальный плеер, то deallocate его */
self.myMusicPlayer = nil;
self.myMusicPlayer = [[MPMusicPlayerController alloc] init];
[self.myMusicPlayer beginGeneratingPlaybackNotifications];
/* Получаем уведомление, когда состояние проигрывания изменится */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerStateChanged:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:self.myMusicPlayer];
/* Получаем уведомление, когда проигрывание переместится от одной мелодии к другой. В данном пример мы разрешаем пользователю выбрать только один музыкальный файл */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(nowPlayingItemIsChanged:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:self.myMusicPlayer];
/* А также получаем уведомление, когда изменяется громкость в музыкальном плеере */
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeIsChanged:) name:MPMusicPlayerControllerVolumeDidChangeNotification object:self.myMusicPlayer];
/* Начинаме проигрывание мелодий из коллекции */
[self.myMusicPlayer setQueueWithItemCollection:mediaItemCollection];
[self.myMusicPlayer play];
/* Наконец освобождаем media picker controller */
[mediaPicker dismissModalViewControllerAnimated:YES];
}
- (void) mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
/* Media picker был отменен */
NSLog(@"Media Picker was cancelled");
[mediaPicker dismissModalViewControllerAnimated:YES];
}
- (void) stopPlayingAudio{
if (self.myMusicPlayer != nil){
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:self.myMusicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:self.myMusicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerVolumeDidChangeNotification object:self.myMusicPlayer];
[self.myMusicPlayer stop];
}
}
- (void) musicPlayerStateChanged:(NSNotification *)paramNotification{
NSLog(@"Player State Changed");
/* Получаем состояние плеера */
NSNumber *stateAsObject = [paramNotification.userInfo
objectForKey:@"MPMusicPlayerControllerPlaybackStateKey"];
NSInteger state = [stateAsObject integerValue];
/* Принимаем решение, базируясь на состоянии плеера */
switch (state){
case MPMusicPlaybackStateStopped:{
/* Здесь media player остановился при проигрывании очереди из мелодий. */
break;
}
case MPMusicPlaybackStatePlaying:{
/* Media player проигрывает очередь. Возможно здесь стоит остановить какие-то процессы, чтобы отдать media player больше процессорных мощностей */
break;
}
case MPMusicPlaybackStatePaused:{
/* Воспроизведение мелодии остановлено. Возможно здесь вы хотите показать какую-то графику пользователю */
break;
}
case MPMusicPlaybackStateInterrupted:{
/* Прерывание остановило воспроизведение мелодий из очереди */
break;
}
case MPMusicPlaybackStateSeekingForward:{
/* Пользователь перематывает очередь мелодий вперед */
break;
}
case MPMusicPlaybackStateSeekingBackward:{
/* Пользователь перематывает очередь мелодий назад */
break;
}
} /* switch (State){ */
}
- (void) nowPlayingItemIsChanged:(NSNotification *)paramNotification{
NSLog(@"Playing Item Is Changed");
NSString *persistentID = [paramNotification.userInfo objectForKey:@"MPMusicPlayerControllerNowPlayingItemPersistentIDKey"];
/* Сделать что-нибудь с Persistent ID */
NSLog(@"Persistent ID = %@", persistentID);
}
- (void) volumeIsChanged:(NSNotification *)paramNotification{
NSLog(@"Volume Is Changed");
/* Массив userInfo обычно пуст */
}
Книга контактов Address Book
Файл RootViewController.h
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
@interface RootViewController : UIViewController
@end
Получение содержимого адресной книги Address Book
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(@"Successfully accessed the address book.");
/* Здесь работаем с адресной книгой */
/* Посмотрим сделали ли мы изменения в адресной книге или нет перед её сохранением */
if (ABAddressBookHasUnsavedChanges(addressBook)){
/*Теперь решаем хотим ли мы сохранить изменения в адресной книге */
NSLog(@"Changes were found in the address book.");
BOOL doYouWantToSaveChanges = YES;
/* Мы можем принять решение сохранить адресную книгу или вернуть её в исходное состояние */
if (doYouWantToSaveChanges){
CFErrorRef saveError = NULL;
if (ABAddressBookSave(addressBook, &saveError)){
/* Мы успешно сохранили наши изменения в адресной книге
address book */
} else {
/* Мы не смогли сохранить изменения в адресной книге. Вы можете посмотреть содержимое переменной [saveError], чтобы узнать в чем была ошибка */
}
} else {
/* Мы не хотим сохранять изменения в адресной книге, поэтому возвращаем её к исходному состоянию */
ABAddressBookRevert(addressBook);
}
} else {
/* Мы не делали никаких изменений в адресной книге */
NSLog(@"No changes to the address book.");
}
CFRelease(addressBook);
} else {
NSLog(@"Could not access the address book.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Получение всех людей из адресной книги Address Book
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(@"Successfully accessed the address book.");
NSArray *arrayOfAllPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [arrayOfAllPeople count];
peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef)[arrayOfAllPeople objectAtIndex:peopleCounter];
NSLog(@"%@", thisPerson);
/* Используйте [thisPerson] address book record */
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Получение свойст из Address Book Entries
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(@"Successfully accessed the address book.");
NSArray *allPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [allPeople count];
peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef) [allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty);
NSString *email = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonEmailProperty);
NSLog(@"First Name = %@", firstName);
NSLog(@"Last Name = %@", lastName);
NSLog(@"Address = %@", email);
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Результат вывода NSLog в консоли:
Successfully accessed the address book.
First Name = Vandad
Last Name = Nahavandipoor
Address = ABMultiValueRef 0x684ad50 with 2 value(s)
0: _$!<Home>!$_ (0x684af00) - vandad.np@gmail.com (0x684af20)
1: _$!<Work>!$_ (0x684aee0) - iosandosx@gmail.com (0x684af90)
First Name = Brian
Last Name = Jepson
Address = ABMultiValueRef 0x684ac00 with 1 value(s)
0: _$!<Home>!$_ (0x684adf0) - brian@oreilly.com (0x684ae10)
First Name = Andy
Last Name = Oram
Address = ABMultiValueRef 0x684a710 with 1 value(s)
0: _$!<Home>!$_ (0x684ace0) - andy@oreilly.com (0x684ad00)
- (void) logPersonEmails:(ABRecordRef)paramPerson{
if (paramPerson == NULL){
NSLog(@"The given person is NULL.");
return;
}
ABMultiValueRef emails = ABRecordCopyValue(paramPerson, kABPersonEmailProperty);
if (emails == NULL){
NSLog(@"This contact does not have any emails.");
return;
}
/* Пройтись по всем email */
NSUInteger emailCounter = 0;
for (emailCounter = 0;
emailCounter < ABMultiValueGetCount(emails);
emailCounter++){
/* Получить label из email (любого) */
NSString *emailLabel = (__bridge_transfer NSString *) ABMultiValueCopyLabelAtIndex(emails, emailCounter);
NSString *localizedEmailLabel = (__bridge_transfer NSString *) ABAddressBookCopyLocalizedLabel((__bridge CFStringRef)emailLabel);
/* И затем получить сам email address */
NSString *email = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(emails, emailCounter);
NSLog(@"Label = %@, Localized Label = %@, Email = %@", emailLabel, localizedEmailLabel, email);
}
CFRelease(emails);
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(@"Successfully accessed the address book.");
NSArray *allPeople = (__bridge_transfer NSArray * ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [allPeople count];
peopleCounter++){
ABRecordRef thisPerson = (__bridge ABRecordRef)[allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(thisPerson, kABPersonLastNameProperty);
NSLog(@"First Name = %@", firstName);
NSLog(@"Last Name = %@", lastName);
[self logPersonEmails:thisPerson];
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Вставка контактных данных в адресную книгу Address Book
- (ABRecordRef) newPersonWithFirstName:(NSString *)paramFirstName lastName:(NSString *)paramLastName inAddressBook:(ABAddressBookRef)paramAddressBook{
ABRecordRef result = NULL;
if (paramAddressBook == NULL){
NSLog(@"The address book is NULL.");
return NULL;
}
if ([paramFirstName length] == 0 && [paramLastName length] == 0){
NSLog(@"First name and last name are both empty.");
return NULL;
}
result = ABPersonCreate();
if (result == NULL){
NSLog(@"Failed to create a new person.");
return NULL;
}
BOOL couldSetFirstName = NO;
BOOL couldSetLastName = NO;
CFErrorRef setFirstNameError = NULL;
CFErrorRef setLastNameError = NULL;
couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty, (__bridge CFTypeRef)paramFirstName, &setFirstNameError);
couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty,(__bridge CFTypeRef)paramLastName, &setLastNameError);
CFErrorRef couldAddPersonError = NULL;
BOOL couldAddPerson = ABAddressBookAddRecord(paramAddressBook, result, &couldAddPersonError);
if (couldAddPerson){
NSLog(@"Successfully added the person.");
} else {
NSLog(@"Failed to add the person.");
CFRelease(result);
result = NULL;
return result;
}
if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
CFErrorRef couldSaveAddressBookError = NULL;
BOOL couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
if (couldSaveAddressBook){
NSLog(@"Successfully saved the address book.");
} else {
NSLog(@"Failed to save the address book.");
}
}
if (couldSetFirstName && couldSetLastName){
NSLog(@"Successfully set the first name and the last name of the person.");
} else {
NSLog(@"Failed to set the first name and/or last name of the person.");
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != NULL){
ABRecordRef anthonyRobbins = [self newPersonWithFirstName:@"Anthony" lastName:@"Robbins" inAddressBook:addressBook];
if (anthonyRobbins != NULL){
NSLog(@"Anthony Robbins' record is inserted into the Address Book.");
CFRelease(anthonyRobbins);
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
/* Переписывание точки кастомизации после запуска приложения */
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Добавление группы записей в адресную книгу Address Book
- (ABRecordRef) newGroupWithName:(NSString *)paramGroupName
inAddressBook:(ABAddressBookRef)paramAddressBook{
ABRecordRef result = NULL;
if (paramAddressBook == NULL){
NSLog(@"The address book is nil.");
return NULL;
}
result = ABGroupCreate();
if (result == NULL){
NSLog(@"Failed to create a new group.");
return NULL;
}
BOOL couldSetGroupName = NO;
CFErrorRef error = NULL;
couldSetGroupName = ABRecordSetValue(result, kABGroupNameProperty,(__bridge CFTypeRef)paramGroupName, &error);
if (couldSetGroupName){
BOOL couldAddRecord = NO;
CFErrorRef couldAddRecordError = NULL;
couldAddRecord = ABAddressBookAddRecord(paramAddressBook, result, &couldAddRecordError);
if (couldAddRecord){
NSLog(@"Successfully added the new group.");
if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
BOOL couldSaveAddressBook = NO;
CFErrorRef couldSaveAddressBookError = NULL;
couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
if (couldSaveAddressBook){
NSLog(@"Successfully saved the address book.");
} else {
CFRelease(result);
result = NULL;
NSLog(@"Failed to save the address book.");
}
} else {
CFRelease(result);
result = NULL;
NSLog(@"No unsaved changes.");
}
} else {
CFRelease(result);
result = NULL;
NSLog(@"Could not add a new group.");
}
} else {
CFRelease(result);
result = NULL;
NSLog(@"Failed to set the name of the group.");
}
return result;
}
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
NSLog(@"Successfully accessed the address book.");
ABRecordRef personalCoachesGroup = [self newGroupWithName:@"Personal Coaches" inAddressBook:addressBook];
if (personalCoachesGroup != NULL){
NSLog(@"Successfully created the group.");
CFRelease(personalCoachesGroup);
} else {
NSLog(@"Could not create the group.");
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Добавление персон в группы адресной книги Address Book
- (BOOL) addPerson:(ABRecordRef)paramPerson toGroup:(ABRecordRef)paramGroup saveToAddressBook (ABAddressBookRef)paramAddressBook{
BOOL result = NO;
if (paramPerson == NULL || paramGroup == NULL || paramAddressBook == NULL){
NSLog(@"Invalid parameters are given.");
return NO;
}
CFErrorRef error = NULL;
/* Теперь добавим персону в группу */
result = ABGroupAddMember(paramGroup, paramPerson, &error);
if (result == NO){
NSLog(@"Could not add the person to the group.");
return result;
}
/* Убедимся, что мы сохранили все изменения */
if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
BOOL couldSaveAddressBook = NO;
CFErrorRef couldSaveAddressBookError = NULL;
couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
if (couldSaveAddressBook){
NSLog(@"Successfully added the person to the group.");
result = YES;
} else {
NSLog(@"Failed to save the address book.");
}
} else {
NSLog(@"No changes were saved.");
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != nil){
ABRecordRef richardBranson = [self newPersonWithFirstName:@"Richard" lastName:@"Branson" inAddressBook:addressBook];
if (richardBranson != NULL){
ABRecordRef entrepreneursGroup = [self newGroupWithName:@"Entrepreneurs" inAddressBook:addressBook];
if (entrepreneursGroup != NULL){
if ([self addPerson:richardBranson toGroup:entrepreneursGroup saveToAddressBook:addressBook]){
NSLog(@"Successfully added Richard Branson to the Entrepreneurs Group");
} else {
NSLog(@"Failed to add Richard Branson to the Entrepreneurs group.");
}
CFRelease(entrepreneursGroup);
} else {
NSLog(@"Failed to create the Entrepreneurs group.");
}
CFRelease(richardBranson);
} else {
NSLog(@"Failed to create an entity for Richard Branson.");
}
CFRelease(addressBook);
} else {
NSLog(@"Address book is nil.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Поиск по адресной книге Address Book
- (BOOL) doesPersonExistWithFirstName:(NSString *)paramFirstName
lastName:(NSString *)paramLastName inAddressBook: (ABRecordRef)paramAddressBook{
BOOL result = NO;
if (paramAddressBook == NULL){
NSLog(@"The address book is null.");
return NO;
}
NSArray *allPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(paramAddressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [allPeople count];
peopleCounter++){
ABRecordRef person = (__bridge ABRecordRef) [allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonLastNameProperty);
BOOL firstNameIsEqual = NO;
BOOL lastNameIsEqual = NO;
if ([firstName length] == 0 && [paramFirstName length] == 0){
firstNameIsEqual = YES;
} else if ([firstName isEqualToString:paramFirstName]){
firstNameIsEqual = YES;
}
if ([lastName length] == 0 && [paramLastName length] == 0){
lastNameIsEqual = YES;
} else if ([lastName isEqualToString:paramLastName]){
lastNameIsEqual = YES;
}
if (firstNameIsEqual && lastNameIsEqual){
return YES;
}
}
return result;
}
- (BOOL) doesGroupExistWithGroupName:(NSString *)paramGroupName
inAddressBook:(ABAddressBookRef)paramAddressBook{
BOOL result = NO;
if (paramAddressBook == NULL){
NSLog(@"The address book is null.");
return NO;
}
NSArray *allGroups = (__bridge_transfer NSArray *)
ABAddressBookCopyArrayOfAllGroups(paramAddressBook);
NSUInteger groupCounter = 0;
for (groupCounter = 0;
groupCounter < [allGroups count];
groupCounter++){
ABRecordRef group = (__bridge ABRecordRef) [allGroups objectAtIndex:groupCounter];
NSString *groupName = (__bridge_transfer NSString *) ABRecordCopyValue(group, kABGroupNameProperty);
if ([groupName length] == 0 && [paramGroupName length] == 0){
return YES;
} else if ([groupName isEqualToString:paramGroupName]){
return YES;
}
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != NULL){
if ([self doesGroupExistWithGroupName:@"O'Reilly" inAddressBook:addressBook]){
NSLog(@"The O'Reilly group already exists in the address book.");
} else {
ABRecordRef oreillyGroup = [self newGroupWithName:@"O'Reilly" inAddressBook:addressBook];
if (oreillyGroup != NULL){
NSLog(@"Successfully created a group for O'Reilly.");
CFRelease(oreillyGroup);
} else {
NSLog(@"Failed to create a group for O'Reilly.");
}
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Пример функции ABAddressBookCopyPeopleWithName для поиска контакта с осбоым именем
- (BOOL) doesPersonExistWithFullName:(NSString *)paramFullName
inAddressBook:(ABAddressBookRef)paramAddressBook{
BOOL result = NO;
if (paramAddressBook == NULL){
NSLog(@"Address book is null.");
return NO;
}
NSArray *allPeopleWithThisName = (__bridge_transfer NSArray *) ABAddressBookCopyPeopleWithName(paramAddressBook, (__bridge CFStringRef)paramFullName);
if ([allPeopleWithThisName count] > 0){
result = YES;
}
return result;
}
- (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != NULL){
if ([self doesPersonExistWithFullName:@"Anthony Robbins" inAddressBook:addressBook]){
NSLog(@"Anthony Robbins exists in the address book.");
} else {
NSLog(@"Anthony Robbins does not exist in the address book.");
ABRecordRef anthonyRobbins = [self newPersonWithFirstName:@"Anthony" lastName:@"Robbins" inAddressBook:addressBook];
if (anthonyRobbins != NULL){
NSLog(@"Successfully created a record for Anthony Robbins");
CFRelease(anthonyRobbins);
} else {
NSLog(@"Failed to create a record for Anthony Robbins");
}
}
CFRelease(addressBook);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Получение и установка картинки персоны в адресной книге Address Book
- (UIImage *) getPersonImage:(ABRecordRef)paramPerson{
UIImage *result = nil;
if (paramPerson == NULL){
NSLog(@"The person is nil.");
return NULL;
}
NSData *imageData = (__bridge_transfer NSData *) ABPersonCopyImageData(paramPerson);
if (imageData != nil){
UIImage *image = [UIImage imageWithData:imageData];
result = image;
}
return result;
}
- (BOOL) setPersonImage:(ABRecordRef)paramPerson inAddressBook:(ABAddressBookRef)paramAddressBook withImageData:(NSData *)paramImageData{
BOOL result = NO;
if (paramAddressBook == NULL){
NSLog(@"The address book is nil.");
return NO;
}
if (paramPerson == NULL){
NSLog(@"The person is nil.");
return NO;
}
CFErrorRef couldSetPersonImageError = NULL;
BOOL couldSetPersonImage = ABPersonSetImageData(paramPerson, (__bridge CFDataRef)paramImageData, &couldSetPersonImageError);
if (couldSetPersonImage){
NSLog(@"Successfully set the person's image. Saving...");
if (ABAddressBookHasUnsavedChanges(paramAddressBook)){
BOOL couldSaveAddressBook = NO;
CFErrorRef couldSaveAddressBookError = NULL;
couldSaveAddressBook = ABAddressBookSave(paramAddressBook, &couldSaveAddressBookError);
if (couldSaveAddressBook){
NSLog(@"Successfully saved the address book.");
result = YES;
} else {
NSLog(@"Failed to save the address book.");
}
} else {
NSLog(@"There are no changes to be saved!");
}
} else {
NSLog(@"Failed to set the person's image.");
}
return result;
}
Файл Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController.h
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
@interface Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController
: UIViewController
@property (nonatomic, strong) UILabel *labelOldImage;
@property (nonatomic, strong) UIImageView *imageViewOld;
@property (nonatomic, strong) UILabel *labelNewImage;
@property (nonatomic, strong) UIImageView *imageViewNew;
@end
Файл Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController.m
#import "Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController.h"
@implementation
Retrieving_and_Setting_a_Person_s_Address_Book_ImageViewController
@synthesize labelOldImage;
@synthesize imageViewOld;
@synthesize labelNewImage;
@synthesize imageViewNew;
- (void) changeYPositionOfView:(UIView *)paramView to:(CGFloat)paramY{
CGRect viewFrame = paramView.frame;
viewFrame.origin.y = paramY;
paramView.frame = viewFrame;
}
- (void) createLabelAndImageViewForOldImage{
self.labelOldImage = [[UILabel alloc] initWithFrame:CGRectZero];
self.labelOldImage.text = @"Old Image";
self.labelOldImage.font = [UIFont systemFontOfSize:16.0f];
[self.labelOldImage sizeToFit];
self.labelOldImage.center = self.view.center;
[self.view addSubview:self.labelOldImage];
[self changeYPositionOfView:self.labelOldImage to:80.0f];
self.imageViewOld = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f,
0.0f,
100.0f,
100.0f)];
self.imageViewOld.center = self.view.center;
self.imageViewOld.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:self.imageViewOld];
[self changeYPositionOfView:self.imageViewOld to:105.0f];
}
- (void) createLabelAndImageViewForNewImage{
self.labelNewImage = [[UILabel alloc] initWithFrame:CGRectZero];
self.labelNewImage.text = @"New Image";
self.labelNewImage.font = [UIFont systemFontOfSize:16.0f];
[self.labelNewImage sizeToFit];
self.labelNewImage.center = self.view.center;
[self.view addSubview:self.labelNewImage];
[self changeYPositionOfView:self.labelNewImage to:210.0f];
self.imageViewNew = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f,
0.0f,
100.0f,
100.0f)];
self.imageViewNew.center = self.view.center;
self.imageViewNew.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:self.imageViewNew];
[self changeYPositionOfView:self.imageViewNew to:235.0f];
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createLabelAndImageViewForOldImage];
[self createLabelAndImageViewForNewImage];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.labelOldImage = nil;
self.imageViewOld = nil;
self.labelNewImage = nil;
self.imageViewNew = nil;
}
- (ABRecordRef) getPersonWithFirstName:(NSString *)paramFirstName
lastName:(NSString *)paramLastName inAddressBook:(ABRecordRef)paramAddressBook{
ABRecordRef result = NULL;
if (paramAddressBook == NULL){
NSLog(@"The address book is null.");
return NULL;
}
NSArray *allPeople = (__bridge_transfer NSArray *) ABAddressBookCopyArrayOfAllPeople(paramAddressBook);
NSUInteger peopleCounter = 0;
for (peopleCounter = 0;
peopleCounter < [allPeople count];
peopleCounter++){
ABRecordRef person = (__bridge ABRecordRef) [allPeople objectAtIndex:peopleCounter];
NSString *firstName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *) ABRecordCopyValue(person, kABPersonLastNameProperty);
BOOL firstNameIsEqual = NO;
BOOL lastNameIsEqual = NO;
if ([firstName length] == 0 && [paramFirstName length] == 0){
firstNameIsEqual = YES;
} else if ([firstName isEqualToString:paramFirstName]){
firstNameIsEqual = YES;
}
if ([lastName length] == 0 && [paramLastName length] == 0){
lastNameIsEqual = YES;
} else if ([lastName isEqualToString:paramLastName]){
lastNameIsEqual = YES;
}
if (firstNameIsEqual && lastNameIsEqual){
return person;
}
}
return result;
}
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createLabelAndImageViewForOldImage];
[self createLabelAndImageViewForNewImage];
ABAddressBookRef addressBook = ABAddressBookCreate();
if (addressBook != NULL){
ABRecordRef anthonyRobbins = [self getPersonWithFirstName:@"Anthony" lastName:@"Robbins" inAddressBook:addressBook];
if (anthonyRobbins == NULL){
NSLog(@"Couldn't find record. Creating one...");
anthonyRobbins = [self newPersonWithFirstName:@"Anthony" lastName:@"Robbins" inAddressBook:addressBook];
if (anthonyRobbins == NULL){
NSLog(@"Failed to create a new record for this person.");
CFRelease(addressBook);
return;
}
}
self.imageViewOld.image = [self getPersonImage:anthonyRobbins];
NSString *newImageFilePath = [[NSBundle mainBundle] pathForResource:@"Anthony Robbins" ofType:@"jpg"];
UIImage *newImage = [[UIImage alloc] initWithContentsOfFile:newImageFilePath];
NSData *newImageData = UIImagePNGRepresentation(newImage);
if ([self setPersonImage:anthonyRobbins inAddressBook:addressBook withImageData:newImageData]){
NSLog(@"Successfully set this person's new image.");
self.imageViewNew.image = [self getPersonImage:anthonyRobbins];
} else {
NSLog(@"Failed to set this person's new image.");
}
CFRelease(anthonyRobbins);
CFRelease(addressBook);
}
}
@end
Обнаружение и проверка работы камеры в устройстве
- (BOOL) isCameraAvailable{
return [UIImagePickerController isSourceTypeAvailable:
UIImagePickerControllerSourceTypeCamera];
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if ([self isCameraAvailable]){
NSLog(@"Camera is available.");
} else {
NSLog(@"Camera is not available.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Файл Detecting_and_Probing_the_CameraAppDelegate.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface Detecting_and_Probing_the_CameraAppDelegate
: UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
Файл Detecting_and_Probing_the_CameraAppDelegate.m
- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType
sourceType:(UIImagePickerControllerSourceType)paramSourceType{
__block BOOL result = NO;
if ([paramMediaType length] == 0){
NSLog(@"Media type is empty.");
return NO;
}
NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
[availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
NSString *mediaType = (NSString *)obj;
if ([mediaType isEqualToString:paramMediaType]){
result = YES;
*stop= YES;
}
}];
return result;
}
- (BOOL) doesCameraSupportShootingVideos{
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
}
- (BOOL) doesCameraSupportTakingPhotos{
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if ([self doesCameraSupportTakingPhotos]){
NSLog(@"The camera supports taking photos.");
} else {
NSLog(@"The camera does not support taking photos");
}
if ([self doesCameraSupportShootingVideos]){
NSLog(@"The camera supports shooting videos.");
} else {
NSLog(@"The camera does not support shooting videos.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL) isFrontCameraAvailable{
return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}
- (BOOL) isRearCameraAvailable{
return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}
- (BOOL) isFlashAvailableOnFrontCamera{
return [UIImagePickerController isFlashAvailableForCameraDevice:
UIImagePickerControllerCameraDeviceFront];
}
- (BOOL) isFlashAvailableOnRearCamera{
return [UIImagePickerController isFlashAvailableForCameraDevice:
UIImagePickerControllerCameraDeviceRear];
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if ([self isFrontCameraAvailable]){
NSLog(@"The front camera is available.");
if ([self isFlashAvailableOnFrontCamera]){
NSLog(@"The front camera is equipped with a flash");
} else {
NSLog(@"The front camera is not equipped with a flash");
}
} else {
NSLog(@"The front camera is not available.");
}
if ([self isRearCameraAvailable]){
NSLog(@"The rear camera is available.");
if ([self isFlashAvailableOnRearCamera]){
NSLog(@"The rear camera is equipped with a flash");
} else {
NSLog(@"The rear camera is not equipped with a flash");
}
} else {
NSLog(@"The rear camera is not available.");
}
if ([self doesCameraSupportTakingPhotos]){
NSLog(@"The camera supports taking photos.");
} else {
NSLog(@"The camera does not support taking photos");
}
if ([self doesCameraSupportShootingVideos]){
NSLog(@"The camera supports shooting videos.");
} else {
NSLog(@"The camera does not support shooting videos.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Результат вывода в консоль функции NSlog:
The front camera is available.
The front camera is not equipped with a flash
The rear camera is available.
The rear camera is equipped with a flash
The camera supports taking photos.
The camera supports shooting videos.
Съемка фотографий на камеру
Файл Taking_Photos_with_the_CameraViewController.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface Taking_Photos_with_the_CameraViewController
: UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate>
@end
Файл Taking_Photos_with_the_CameraViewController.m
- (void)viewDidLoad{
[super viewDidLoad];
if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
NSString *requiredMediaType = (__bridge NSString *)kUTTypeImage;
controller.mediaTypes = [[NSArray alloc] initWithObjects:requiredMediaType, nil];
controller.allowsEditing = YES;
controller.delegate = self;
[self.navigationController presentModalViewController:controller animated:YES];
} else {
NSLog(@"Camera is not available.");
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"Picker returned successfully.");
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeMovie]){
NSURL *urlOfVideo = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"Video URL = %@", urlOfVideo);
} else if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage]){
/* Теперь получим metadata. Metadata нужны только для картинок. Не для видео. */
NSDictionary *metadata = [info objectForKey: UIImagePickerControllerMediaMetadata];
UIImage *theImage = [info objectForKey: UIImagePickerControllerOriginalImage];
NSLog(@"Image Metadata = %@", metadata);
NSLog(@"Image = %@", theImage);
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"Picker was cancelled");
[picker dismissModalViewControllerAnimated:YES];
}
Съемка видео на камеру
- (void)viewDidLoad{
[super viewDidLoad];
if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
NSString *requiredMediaType = (__bridge NSString *)kUTTypeMovie;
controller.mediaTypes = [[NSArray alloc] initWithObjects:requiredMediaType, nil];
controller.allowsEditing = YES;
controller.delegate = self;
[self.navigationController presentModalViewController:controller animated:YES];
} else {
NSLog(@"Camera is not available.");
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"Picker returned successfully.");
NSLog(@"%@", info);
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeMovie]){
NSURL *urlOfVideo = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(@"Video URL = %@", urlOfVideo);
NSError *dataReadingError = nil;
NSData *videoData = [NSData dataWithContentsOfURL:urlOfVideo options:NSDataReadingMapped error:&dataReadingError];
if (videoData != nil){
/* Мы готовы прочитать данные. */
NSLog(@"Successfully loaded the data.");
} else {
/* Мы не смогли прочитать данные. Исмпользуем переменную dataReadingError для определения ошибки */
NSLog(@"Failed to load the data with error = %@", dataReadingError);
}
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"Picker was cancelled");
[picker dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad{
[super viewDidLoad];
if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
NSString *requiredMediaType = (__bridge NSString *)kUTTypeMovie;
controller.mediaTypes = [[NSArray alloc] initWithObjects:requiredMediaType, nil];
controller.allowsEditing = YES;
controller.delegate = self;
/* Запись в высоком качестве */
controller.videoQuality = UIImagePickerControllerQualityTypeHigh;
/* Разрешено записывать только 30 секунд */
controller.videoMaximumDuration = 30.0f;
[self.navigationController presentModalViewController:controller
animated:YES];
} else {
NSLog(@"Camera is not available.");
}
}
Хранение фотографии в библиотеке фотографий Photo Library
- (void) imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{
if (paramError == nil){
NSLog(@"Image was saved successfully.");
} else {
NSLog(@"An error happened while saving the image.");
NSLog(@"Error = %@", paramError);
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"Picker returned successfully.");
NSLog(@"%@", info);
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeImage]){
UIImage *theImage = nil;
if ([picker allowsEditing]){
theImage = [info objectForKey:UIImagePickerControllerEditedImage];
} else {
theImage = [info objectForKey:UIImagePickerControllerOriginalImage];
}
SEL selectorToCall = @selector(imageWasSavedSuccessfully:didFinishSavingWithError:contextInfo:);
UIImageWriteToSavedPhotosAlbum(theImage, self, selectorToCall, NULL);
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"Picker was cancelled");
[picker dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad{
[super viewDidLoad];
if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypeCamera;
NSString *requiredMediaType = (__bridge NSString *)kUTTypeImage;
controller.mediaTypes = [[NSArray alloc] initWithObjects:requiredMediaType, nil];
controller.allowsEditing = YES;
controller.delegate = self;
[self.navigationController presentModalViewController:controller animated:YES];
} else {
NSLog(@"Camera is not available.");
}
}
- (void) imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{
if (paramError == nil){
NSLog(@"Image was saved successfully.");
} else {
NSLog(@"An error happened while saving the image.");
NSLog(@"Error = %@", paramError);
}
}
Хранение видео в библиотеке фотографий Photo Library
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
NSURL *videoURL = [[NSBundle mainBundle] URLForResource:@"MyVideo"
withExtension:@"MOV"];
if (videoURL != nil){
[self.assetsLibrary writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error == nil){
NSLog(@"no errors happened");
} else {
NSLog(@"Error happened while saving the video.");
NSLog(@"The error is = %@", error);
}
}];
} else {
NSLog(@"Could not find the video in the app bundle.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Получение фото и видео из библиотеки Photo Library
- (BOOL) isPhotoLibraryAvailable{
return [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)viewDidLoad{
[super viewDidLoad];
if ([self isPhotoLibraryAvailable]){
UIImagePickerController *controller = [[UIImagePickerController alloc] init];
controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
if ([self canUserPickPhotosFromPhotoLibrary]){
[mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
}
if ([self canUserPickVideosFromPhotoLibrary]){
[mediaTypes addObject:(__bridge NSString *)kUTTypeMovie];
}
controller.mediaTypes = mediaTypes;
controller.delegate = self;
[self.navigationController presentModalViewController:controller animated:YES];
}
}
Получение Assets из Assets Library для фото
- (void)viewDidLoad{
[super viewDidLoad];
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
[self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
/* Получить тип asset */
NSString *assetType = [result valueForProperty:ALAssetPropertyType];
if ([assetType isEqualToString:ALAssetTypePhoto]){
NSLog(@"This is a photo asset");
} else if ([assetType isEqualToString:ALAssetTypeVideo]){
NSLog(@"This is a video asset");
} else if ([assetType isEqualToString:ALAssetTypeUnknown]){
NSLog(@"This is an unknown asset");
}
/* Получить URL для asset */
NSDictionary *assetURLs = [result valueForProperty:ALAssetPropertyURLs];
NSUInteger assetCounter = 0;
for (NSString *assetURLKey in assetURLs){
assetCounter++;
NSLog(@"Asset URL %lu = %@", (unsigned long)assetCounter, [assetURLs valueForKey:assetURLKey]);
}
/* Получить asset's representation object */
ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];
NSLog(@"Representation Size = %lld", [assetRepresentation size]);
}];
}
failureBlock:^(NSError *error) {
NSLog(@"Failed to enumerate the asset groups.");
}];
}
- (void)viewDidUnload{
[super viewDidUnload];
self.assetsLibrary = nil;
}
Файл Retrieving_Assets_from_the_Assets_LibraryViewController.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface Retrieving_Assets_from_the_Assets_LibraryViewController
: UIViewController <UIImagePickerControllerDelegate,
UINavigationControllerDelegate>
@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) UIImageView *imageView;
@end
Файл Retrieving_Assets_from_the_Assets_LibraryViewController.m
#import "Retrieving_Assets_from_the_Assets_LibraryViewController.h"
@implementation Retrieving_Assets_from_the_Assets_LibraryViewController
@synthesize assetsLibrary;
@synthesize imageView;
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
[self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
__block BOOL foundThePhoto = NO;
if (foundThePhoto){
*stop = YES;
}
/* Поучить тип asset */
NSString *assetType = [result valueForProperty:ALAssetPropertyType];
if ([assetType isEqualToString:ALAssetTypePhoto]){
NSLog(@"This is a photo asset");
foundThePhoto = YES;
*stop = YES;
/* Получить asset's representation object */
ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];
/* Нам нужно изменить масштабирование и ориентацию для правильного конструирования объекта UIImage */
CGFloat imageScale = [assetRepresentation scale];
UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];
dispatch_async(dispatch_get_main_queue(), ^(void) {
CGImageRef imageReference = [assetRepresentation fullResolutionImage];
/* Создание картинки */
UIImage *image = [[UIImage alloc] initWithCGImage:imageReference scale:imageScale orientation:imageOrientation];
if (image != nil){
self.imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.imageView.image = image;
[self.view addSubview:self.imageView];
} else {
NSLog(@"Failed to create the image.");
}
});
}
}];
}
failureBlock:^(NSError *error) {
NSLog(@"Failed to enumerate the asset groups.");
}];
});
}
- (void)viewDidUnload{
[super viewDidUnload];
self.assetsLibrary = nil;
self.imageView = nil;
}
@end
Получение Assets из Assets Library для видео
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.assetsLibrary = [[ALAssetsLibrary alloc] init];
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
[self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
__block BOOL foundTheVideo = NO;
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
/* Получить тип asset */
NSString *assetType = [result valueForProperty:ALAssetPropertyType];
if ([assetType isEqualToString:ALAssetTypeVideo]){
NSLog(@"This is a video asset");
foundTheVideo = YES;
*stop = YES;
/* Получить asset's representation object */
ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];
const NSUInteger BufferSize = 1024;
uint8_t buffer[BufferSize];
NSUInteger bytesRead = 0;
long long currentOffset = 0;
NSError *readingError = nil;
/* Найти папку с документами (массив) */
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
/* Получить одну папку с документами, которая нам нужна */
NSString *documentsFolder = [documents objectAtIndex:0];
/* Создать путь куда сохранено видео */
NSString *videoPath = [documentsFolder stringByAppendingPathComponent:@"Temp.MOV"];
NSFileManager *fileManager = [[NSFileManager alloc] init];
/* Создать файл, если он еще не существует */
if ([fileManager fileExistsAtPath:videoPath] == NO){
[fileManager createFileAtPath:videoPath contents:nil attributes:nil];
}
/* Мы будем использовать файл для записи содержимого media assets на диск */
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:videoPath];
do{
/* Прочитать столько байт, сколько поместится в буфер */
bytesRead = [assetRepresentation getBytes:(uint8_t *)&buffer fromOffset:currentOffset length:BufferSize error:&readingError];
/* Если мы не можем прочитать ничего, то выйти из цикла */
if (bytesRead == 0){
break;
}
/* Сохранить offset up to date */
currentOffset += bytesRead;
/* Положить буфер в NSData */
NSData *readData = [[NSData alloc] initWithBytes:(const void *)buffer length:bytesRead];
/* И записать данные в файл */
[fileHandle writeData:readData];
} while (bytesRead > 0);
NSLog(@"Finished reading and storing the video in the documents folder");
}
}];
if (foundTheVideo){
*stop = YES;
}
}
failureBlock:^(NSError *error) {
NSLog(@"Failed to enumerate the asset groups.");
}];
});
}
- (void)viewDidUnload{
[super viewDidUnload];
self.assetsLibrary = nil;
}
Редактирование видео
Файл Editing_Videos_on_an_iOS_DeviceViewController.h
#import <UIKit/UIKit.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
@interface Editing_Videos_on_an_iOS_DeviceViewController
: UIViewController <UINavigationControllerDelegate,
UIVideoEditorControllerDelegate,
UIImagePickerControllerDelegate>
@property (nonatomic, strong) NSURL *videoURLToEdit;
@end
Файл Editing_Videos_on_an_iOS_DeviceViewController.m
#import "Editing_Videos_on_an_iOS_DeviceViewController.h"
@implementation Editing_Videos_on_an_iOS_DeviceViewController
@synthesize videoURLToEdit;
- (void)videoEditorController:(UIVideoEditorController *)editor didSaveEditedVideoToPath:(NSString *)editedVideoPath{
NSLog(@"The video editor finished saving video");
NSLog(@"The edited video path is at = %@", editedVideoPath);
[editor dismissModalViewControllerAnimated:YES];
}
- (void)videoEditorController:(UIVideoEditorController *)editor didFailWithError:(NSError *)error{
NSLog(@"Video editor error occurred = %@", error);
[editor dismissModalViewControllerAnimated:YES];
}
- (void)videoEditorControllerDidCancel:(UIVideoEditorController *)editor{
NSLog(@"The video editor was cancelled");
[editor dismissModalViewControllerAnimated:YES];
}
- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
__block BOOL result = NO;
if ([paramMediaType length] == 0){
NSLog(@"Media type is empty.");
return NO;
}
NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
[availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
NSString *mediaType = (NSString *)obj;
if ([mediaType isEqualToString:paramMediaType]){
result = YES;
*stop= YES;
}
}];
return result;
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie
sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) isPhotoLibraryAvailable{
return [UIImagePickerController
isSourceTypeAvailable:
UIImagePickerControllerSourceTypePhotoLibrary];
}
- (void)viewDidLoad {
[super viewDidLoad];
if ([self isPhotoLibraryAvailable] && [self canUserPickVideosFromPhotoLibrary]){
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
/* Установить тип источника для photo library */
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
/* Мы хотим чтобы пользователь мог выбирать видео из билиотеки */
NSArray *mediaTypes = [[NSArray alloc] initWithObjects: (__bridge NSString *)kUTTypeMovie, nil];
imagePicker.mediaTypes = mediaTypes;
/* Установка делегата для текущего view controller */
imagePicker.delegate = self;
/* Представление нашего image picker */
[self.navigationController presentModalViewController:imagePicker animated:YES];
}
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"Picker returned successfully.");
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
self.videoURLToEdit = [info objectForKey:UIImagePickerControllerMediaURL];
}
[picker dismissModalViewControllerAnimated:YES];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
NSLog(@"Picker was cancelled");
self.videoURLToEdit = nil;
[picker dismissModalViewControllerAnimated:YES];
}
- (void) viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
if (self.videoURLToEdit != nil){
NSString *videoPath = [self.videoURLToEdit path];
/* Сперва убедимся, что видеоредактор может редактировать путь к видео в папке */
if ([UIVideoEditorController canEditVideoAtPath:videoPath]){
/* Создаем видеорадектор */
UIVideoEditorController *videoEditor = [[UIVideoEditorController alloc] init];
/* Становимся делегатом нашего видеоредактора */
videoEditor.delegate = self;
/* Устанавливаем путь к видео */
videoEditor.videoPath = videoPath;
/* И показываем наш видеоредактор */
[self.navigationController presentModalViewController:videoEditor animated:YES];
self.videoURLToEdit = nil;
} else {
NSLog(@"Cannot edit the video at this path");
}
}
}
@end
Обнаружение возможности использования много задачности Multitasking
- (BOOL) isMultitaskingSupported{
BOOL result = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){
result = [[UIDevice currentDevice] isMultitaskingSupported];
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if ([self isMultitaskingSupported]){
NSLog(@"Multitasking is supported.");
} else {
NSLog(@"Multitasking is not supported.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Завершение долго выполняющейся задачи в бэкграунде
Файл Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate.h
#import <UIKit/UIKit.h>
@interface Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate
: UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, unsafe_unretained)
UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;
@end
Файл Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate.m
#import "Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate.h"
@implementation Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate
@synthesize window = _window;
@synthesize backgroundTaskIdentifier;
@synthesize myTimer;
- (BOOL) isMultitaskingSupported{
BOOL result = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){
result = [[UIDevice currentDevice] isMultitaskingSupported];
}
return result;
}
- (void) timerMethod:(NSTimer *)paramSender{
NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
if (backgroundTimeRemaining == DBL_MAX){
NSLog(@"Background Time Remaining = Undetermined");
} else {
NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);
}
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
if ([self isMultitaskingSupported] == NO){
return;
}
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
[self endBackgroundTask];
}];
}
- (void) endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
__weak Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^(void) {
Completing_a_Long_Running_Task_in_the_BackgroundAppDelegate *strongSelf = weakSelf;
if (strongSelf != nil){
[strongSelf.myTimer invalidate];
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}
});
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){
[self endBackgroundTask];
}
}
@end
Получение локальных уведомлений в бэкграунде
- (BOOL) localNotificationWithMessage:(NSString *)paramMessage actionButtonTitle:(NSString *)paramActionButtonTitle launchImage:(NSString *)paramLaunchImage applicationBadge:(NSInteger)paramApplicationBadge secondsFromNow:(NSTimeInterval)paramSecondsFromNow userInfo:(NSDictionary *)paramUserInfo{
if ([paramMessage length] == 0){
return NO;
}
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = paramMessage;
notification.alertAction = paramActionButtonTitle;
if ([paramActionButtonTitle length]> 0){
/* Убежимся что у на есть кнопка, нажав на которую пользователь запустит наше приложение */
notification.hasAction = YES;
} else {
notification.hasAction = NO;
}
/* Здесь у вас ест шанс изменить загрузочное изображение вашего приложения, когда уведомление просматривается пользователем */
notification.alertLaunchImage = paramLaunchImage;
/* Изменитьbadge number приложения как только уведомление будет показано пользователю. Даже, если пользователь пропустит уведомление, badge number приложения все равно изменится */
notification.applicationIconBadgeNumber = paramApplicationBadge;
/* Хэш-массив будет передан в приложение позже, если пользователь решит посмотреть уведомление */
notification.userInfo = paramUserInfo;
/* Нам надо получить system time zone для того, чтобы alert view дал настроить свою fire date, если пользователь изменитtime zone */
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
notification.timeZone = timeZone;
/* Расписание отправки сообщения 10 секунд спустя сейчас */
NSDate *today = [NSDate date];
NSDate *fireDate = [today dateByAddingTimeInterval:paramSecondsFromNow];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSUInteger dateComponents =
NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit;
NSDateComponents *components = [calendar components:dateComponents
fromDate:fireDate];
/* Здесь у вас есть возможность изменить эти компоненты. Вот почему мы получали компоненты даты в первый раз. */
fireDate = [calendar dateFromComponents:components];
/* Наконец, мы устанавливаем расписание дыты отправки уведомлений */
notification.fireDate = fireDate;
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
return YES;
}
Файл Receiving_Local_Notifications_in_the_BackgroundAppDelegate.h
#import <UIKit/UIKit.h>
@interface Receiving_Local_Notifications_in_the_BackgroundAppDelegate
: UIResponder <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
Файл Receiving_Local_Notifications_in_the_BackgroundAppDelegate.m
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
id scheduledLocalNotification = [launchOptions valueForKey: UIApplicationLaunchOptionsLocalNotificationKey];
if (scheduledLocalNotification != nil){
/* Мы получили локальное уведомление пока наше приложение не было запущено. Сейчас вы можете передать переменую ScheduledLocalNotification в UILocalNotification и использовать ее в приложении */
NSString *message = @"Local Notification Woke Us Up";
[[[UIAlertView alloc] initWithTitle:@"Notification" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
} else {
NSString *message =@"A new instant message is available. Would you like to read this message?";
/* Если локальное уведомление не запустило наше приложение, тогда мы стартуем новое локальное уведомление */
[self localNotificationWithMessage:message actionButtonTitle:@"Yes" launchImage:nil applicationBadge:1 secondsFromNow:10.0f userInfo:nil];
message = @"A new Local Notification is set up to be displayed 10 seconds from now";
[[[UIAlertView alloc] initWithTitle:@"Set Up" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}
return YES;
}
- (void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
NSString *message = @"The Local Notification is delivered.";
[[[UIAlertView alloc] initWithTitle:@"Local Notification" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}
Проигрывание аудио в бэкграунде
В файл .plist измените
<dict>
...
...
...
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
...
...
...
</dict>
Файл Playing_Audio_in_the_BackgroundAppDelegate.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface Playing_Audio_in_the_BackgroundAppDelegate
: UIResponder <UIApplicationDelegate, AVAudioPlayerDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end
Файл Playing_Audio_in_the_BackgroundAppDelegate.m
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
dispatch_queue_t dispatchQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSError *audioSessionError = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession setCategory:AVAudioSessionCategoryPlayback
error:&audioSessionError]){
NSLog(@"Successfully set the audio session.");
} else {
NSLog(@"Could not set the audio session");
}
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MySong" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
/* Запуск audio player */
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
/* Мы получили instance AVAudioPlayer? */
if (self.audioPlayer != nil){
/* Установить делегата длятначала проигрывания */
self.audioPlayer.delegate = self;
if ([self.audioPlayer prepareToPlay] && [self.audioPlayer play]){
NSLog(@"Successfully started playing...");
} else {
NSLog(@"Failed to play.");
}
} else {
/* Мы не смогли instantiate AVAudioPlayer */
}
});
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Управление изменением местоположения в бэкграунде
В файл .plist измените
<dict>
...
...
...
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
...
...
...
</dict>
Файл Handling_Location_Changes_in_the_BackgroundAppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface Handling_Location_Changes_in_the_BackgroundAppDelegate
: UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) CLLocationManager *myLocationManager;
@property (nonatomic, unsafe_unretained, getter=isExecutingInBackground)
BOOL executingInBackground;
@end
Файл Handling_Location_Changes_in_the_BackgroundAppDelegate.m
#import "Handling_Location_Changes_in_the_BackgroundAppDelegate.h"
@implementation Handling_Location_Changes_in_the_BackgroundAppDelegate
@synthesize window = _window;
@synthesize myLocationManager;
@synthesize executingInBackground;
- (BOOL) isExecutingInBackground{
return executingInBackground;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.myLocationManager = [[CLLocationManager alloc] init];
self.myLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.myLocationManager.delegate = self;
[self.myLocationManager startUpdatingLocation];
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
self.executingInBackground = YES;
/* Уменьшение точности определения местоположения пока приложение в бэкграунде */
self.myLocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
self.executingInBackground = NO;
/* Увеличение точности определения местоположения пока приложение на экране */
self.myLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
if ([self isExecutingInBackground]){
/* Мы в бэкграунде. Не делать затратных вычислений. */
} else {
/* Мы на экране. Делайте что хотите. */
}
}
@end
Сохраннение и загрузка состояния при многопоточности
Состояния работы приложения:
1) application:didFinishLaunchingWithOptions:
2) applicationDidBecomeActive:
3) applicationWillResignActive:
4) applicationDidEnterBackground:
5) applicationWillEnterForeground:
6) applicationDidBecomeActive:
Файл Saving_and_Loading_the_State_of_Multitasking_iOS_AppsAppDelegate.h
#import <UIKit/UIKit.h>
@interface Saving_and_Loading_the_State_of_Multitasking_iOS_AppsAppDelegate
: UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
/* Методы сохранения состояния нашего приложения */
- (void) saveUserScore;
- (void) saveLevelToDisk;
- (void) pauseGameEngine;
/* Методы загрузки и восстановления состояния нашего приложения */
- (void) loadUserScore;
- (void) loadLevelFromDisk;
- (void) resumeGameEngine;
@end
Файл Saving_and_Loading_the_State_of_Multitasking_iOS_AppsAppDelegate.m
#import "Saving_and_Loading_the_State_of_Multitasking_iOS_AppsAppDelegate.h"
@implementation
Saving_and_Loading_the_State_of_Multitasking_iOS_AppsAppDelegate
@synthesize window = _window;
- (void) saveUserScore{
/* Сохранение очков пользовтеля */
}
- (void) saveLevelToDisk{
/*Сохранение текущего уровня и положения пользовтеля на карте на диск */
}
- (void) pauseGameEngine{
/* Установка работы игрового движка на паузу */
}
- (void) loadUserScore{
/* Загрузка местоположения пользователя обратно в память */
}
- (void) loadLevelFromDisk{
/* Загрузка уровня */
}
- (void) resumeGameEngine{
/* Воостановление работы игрового движка */
}
- (void)applicationWillResignActive:(UIApplication *)application{
[self pauseGameEngine];
}
- (void)applicationDidBecomeActive:(UIApplication *)application{
[self resumeGameEngine];
}
- (void)applicationDidEnterBackground:(UIApplication *)application{
[self saveUserScore];
[self saveLevelToDisk];
[self pauseGameEngine];
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
[self loadUserScore];
[self loadLevelFromDisk];
[self resumeGameEngine];
}
@end
Управление иентернет-соединением в бэкграунде
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions{
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ([data length] > 0 && error != nil){
/* Date did come back */
}
else if ([data length] == 0 &&
error != nil){
/* No data came back */
}
else if (error != nil){
/* Error happened. Make sure you handle this properly */
}
}];
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
/* Replace this URL with the URL of a file that is rather big in size */
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *connectionData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:nil if ([connectionData length] > 0 &&
error == nil){
}
else if ([connectionData length] == 0 &&
error == nil){
}
else if (error != nil){
}
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
dispatch_queue_t dispatchQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
/* Replace this URL with the URL of a file that is rather big in size */
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *connectionData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:nil if ([connectionData length] > 0 &&
error == nil){
}
else if ([connectionData length] == 0 &&
error == nil){
}
else if (error != nil){
}
});
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Управление доставкой уведомлений в просыпающемся приложении
Файл Handling_Notifications_Delivered_to_a_Waking_AppViewController.m
#import "Handling_Notifications_Delivered_to_a_Waking_AppViewController.h"
@implementation Handling_Notifications_Delivered_to_a_Waking_AppViewController
- (void) orientationChanged:(NSNotification *)paramNotification{
NSLog(@"Orientation Changed");
}
- (void)viewDidLoad{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
- (void)viewDidUnload{
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
@end
Реагирование на изменение настрое приложения в App Settings
Файл Responding_to_Changes_in_App_SettingsAppDelegate.m
#import "Responding_to_Changes_in_App_SettingsAppDelegate.h"
@implementation Responding_to_Changes_in_App_SettingsAppDelegate
@synthesize window = _window;
- (void) settingsChanged:(NSNotification *)paramNotification{
NSLog(@"Settings changed");
NSLog(@"Notification Object = %@", [paramNotification object]);
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingsChanged:) name:NSUserDefaultsDidChangeNotification
object:nil];
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillTerminate:(UIApplication *)application{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
Создание и сохранение данных в базе данных Core Data
Файл Creating_and_Saving_Data_Using_Core_DataAppDelegate.m
#import "Creating_and_Saving_Data_Using_Core_DataAppDelegate.h"
#import "Person.h"
@implementation Creating_and_Saving_Data_Using_Core_DataAppDelegate
@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
if (newPerson != nil){
newPerson.firstName = @"Anthony";
newPerson.lastName = @"Robbins";
newPerson.age = [NSNumber numberWithUnsignedInteger:51];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]){
NSLog(@"Successfully saved the context.");
} else {
NSLog(@"Failed to save the context. Error = %@", savingError);
}
} else {
NSLog(@"Failed to create the new person.");
}
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
@end
Чтение данных из базы данных Core Data
- (BOOL) createNewPersonWithFirstName:(NSString *)paramFirstName
lastName:(NSString *)paramLastName age:(NSUInteger)paramAge{
BOOL result = NO;
if ([paramFirstName length] == 0 || [paramLastName length] == 0){
NSLog(@"First and Last names are mandatory.");
return NO;
}
Person *newPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
if (newPerson == nil){
NSLog(@"Failed to create the new person.");
return NO;
}
newPerson.firstName = paramFirstName;
newPerson.lastName = paramLastName;
newPerson.age = [NSNumber numberWithUnsignedInteger:paramAge];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]){
return YES;
} else {
NSLog(@"Failed to save the new person. Error = %@", savingError);
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self createNewPersonWithFirstName:@"Anthony" lastName:@"Robbins" age:51];
[self createNewPersonWithFirstName:@"Richard" lastName:@"Branson" age:61];
/* Сперва создадим запрос для получения данных */
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
/* Здесь мы храним сущности, содержимое которых хотим прочитать */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
/* Говорим, что мы хотит прочитать содержимое Person */
[fetchRequest setEntity:entity];
NSError *requestError = nil;
/* И выполняем запрос для получения содержимого */
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&requestError];
/* Убеждаемся в том, что получили массив */
if ([persons count] > 0){
/* Проходим по всем персонам */
NSUInteger counter = 1;
for (Person *thisPerson in persons){
NSLog(@"Person %lu First Name = %@", (unsigned long)counter, thisPerson.firstName);
NSLog(@"Person %lu Last Name = %@", (unsigned long)counter, thisPerson.lastName);
NSLog(@"Person %lu Age = %ld", (unsigned long)counter, (unsigned long)[thisPerson.age unsignedIntegerValue]);
counter++;
}
} else {
NSLog(@"Could not find any Person entities in the context.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Удаление данных из базы данных Core Data
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self createNewPersonWithFirstName:@"Anthony" lastName:@"Robbins" age:51];
[self createNewPersonWithFirstName:@"Richard" lastName:@"Branson" age:61];
/* Создание запроса на получение данных */
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
/* Прописываем сущности, содержимое которых мы хотим прочитать */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
/* Говорим, что мы хотит прочитать содержимое Person */
[fetchRequest setEntity:entity];
NSError *requestError = nil;
/* И выполняем запрос для получения содержимого */
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
/* Убеждаемся, что получили массив*/
if ([persons count] > 0){
/* Удаляем последнюю персону из массива */
Person *lastPerson = [persons lastObject];
[self.managedObjectContext deleteObject:lastPerson];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]){
NSLog(@"Successfully deleted the last person in the array.");
} else {
NSLog(@"Failed to delete the last person in the array.");
}
} else {
NSLog(@"Could not find any Person entities in the context.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self createNewPersonWithFirstName:@"Anthony" lastName:@"Robbins" age:51];
[self createNewPersonWithFirstName:@"Richard" lastName:@"Branson" age:61];
/* Создание запроса на получение данных */
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
/* Прописываем сущности, содержимое которых мы хотим прочитать */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
/* Говорим, что мы хотит прочитать содержимое Person */
[fetchRequest setEntity:entity];
NSError *requestError = nil;
/* И выполняем запрос для получения содержимого */
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
/* Убеждаемся, что получили массив */
if ([persons count] > 0){
/* Удаляем последнюю персону из массива */
Person *lastPerson = [persons lastObject];
[self.managedObjectContext deleteObject:lastPerson];
if ([lastPerson isDeleted]){
NSLog(@"Successfully deleted the last person...");
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]){
NSLog(@"Successfully saved the context.");
} else {
NSLog(@"Failed to save the context.");
}
} else {
NSLog(@"Failed to delete the last person.");
}
} else {
NSLog(@"Could not find any Person entities in the context.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
В консоли будет выведено через NSLog:
Successfully deleted the last person...
Successfully saved the context.
Сортировка данных в базе данных Core Data
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self createNewPersonWithFirstName:@"Richard" lastName:@"Branson" age:61];
[self createNewPersonWithFirstName:@"Anthony" lastName:@"Robbins" age:51];
/* Сздание запроса для получения данных */
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
/* Создание сущности, содержимое которой мы хотим получить */
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSSortDescriptor *firstNameSort = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: ageSort, firstNameSort, nil];
fetchRequest.sortDescriptors = sortDescriptors;
/* Говорим, что мы хотит прочитать содержимое Person */
[fetchRequest setEntity:entity];
NSError *requestError = nil;
/* И выполняем запрос для получения содержимого */
NSArray *persons = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
for (Person *person in persons){
NSLog(@"First Name = %@", person.firstName);
NSLog(@"Last Name = %@", person.lastName);
NSLog(@"Age = %lu", (unsigned long)[person.age unsignedIntegerValue]);
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
NSSortDescriptor *ageSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
Получаем список календарей
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
EKEventStore *eventStore = [[EKEventStore alloc] init];
/* Это типы календарей в iOS Device. Обратите внимание, что типом объекта EKCalendar является тип EKCalendarType. Хгначения в массиве "CalendarTypes"
точно отражают теже значения в перечислении EKCalendarType
enumeration, но в качестве значений NSString values */
NSArray *calendarTypes = [[NSArray alloc] initWithObjects:
@"Local",
@"CalDAV",
@"Exchange",
@"Subscription",
@"Birthday",
nil];
/* Проходим по всем календарям */
NSUInteger counter = 1;
for (EKCalendar *thisCalendar in eventStore.calendars){
/* Заголовок календаря */
NSLog(@"Calendar %lu Title = %@", (unsigned long)counter, thisCalendar.title);
/* Тип календаря */
NSLog(@"Calendar %lu Type = %@", (unsigned long)counter, [calendarTypes objectAtIndex:thisCalendar.type]);
/* Цвет календаря */
NSLog(@"Calendar %lu Color = %@", (unsigned long)counter, [UIColor colorWithCGColor:thisCalendar.CGColor]);
/* И может ли календарь быть изменен или нет */
if ([thisCalendar allowsContentModifications]){
NSLog(@"Calendar %lu can be modified.", (unsigned long)counter);
} else {
NSLog(@"Calendar %lu cannot be modified.", (unsigned long)counter);
}
counter++;
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
В результате в консоль будет выведено из NSLog:
Calendar 1 Title = Birthdays
Calendar 1 Type = Birthday
Calendar 1 Color = UIDeviceRGBColorSpace 0.509804 0.584314 0.686275 1
Calendar 1 cannot be modified.
Calendar 2 Title = Calendar
Calendar 2 Type = Local
Calendar 2 Color = UIDeviceRGBColorSpace 0.054902 0.380392 0.72549 1
Calendar 2 can be modified.
Calendar 3 Title = Calendar
Calendar 3 Type = CalDAV
Calendar 3 Color = UIDeviceRGBColorSpace 0.054902 0.380392 0.72549 1
Calendar 3 can be modified.
Calendar 4 Title = Home
Calendar 4 Type = CalDAV
Calendar 4 Color = UIDeviceRGBColorSpace 0.443137 0.101961 0.462745 1
Calendar 4 can be modified.
Calendar 5 Title = Work
Calendar 5 Type = CalDAV
Calendar 5 Color = UIDeviceRGBColorSpace 0.964706 0.309804 0 1
Calendar 5 can be modified.
Calendar 6 Title = vandad.np@gmail.com
Calendar 6 Type = CalDAV
Calendar 6 Color = UIDeviceRGBColorSpace 0.160784 0.321569 0.639216 1
Calendar 6 can be modified.
Добавление событий в календари
- (BOOL) createEventWithTitle:(NSString *)paramTitle startDate:(NSDate *)paramStartDate endDate:(NSDate *)paramEndDate inCalendarWithTitle:(NSString *)paramCalendarTitle inCalendarWithType:(EKCalendarType)paramCalendarType notes:(NSString *)paramNotes{
BOOL result = NO;
EKEventStore *eventStore = [[EKEventStore alloc] init];
/* Есть ли еще доступные календари для event store? */
if ([eventStore.calendars count] == 0){
NSLog(@"No calendars are found.");
return NO;
}
EKCalendar *targetCalendar = nil;
/* Попробуем найти календарь, который запросил пользователь */
for (EKCalendar *thisCalendar in eventStore.calendars){
if ([thisCalendar.title isEqualToString:paramCalendarTitle] && thisCalendar.type == paramCalendarType){
targetCalendar = thisCalendar;
break;
}
}
/* Убеждаемся, что мы нашли правильный календарь */
if (targetCalendar == nil){
NSLog(@"Could not find the requested calendar.");
return NO;
}
/* Если календарь не допускает изменений своего содержимого, тогда мы не можем вставить ничего в него */
if (targetCalendar.allowsContentModifications == NO){
NSLog(@"The selected calendar does not allow modifications.");
return NO;
}
/* Создаем событие */
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.calendar = targetCalendar;
/* Устанвливаем свойства события, такие как title, start date/time, date/time и так далее */
event.title = paramTitle;
event.notes = paramNotes;
event.startDate = paramStartDate;
event.endDate = paramEndDate;
/* Наконец, сохраняем событие в календаре */
NSError *saveError = nil;
result = [eventStore saveEvent:event span:EKSpanThisEvent error:&saveError];
if (result == NO){
NSLog(@"An error occurred = %@", saveError);
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
/* Событие начинается сегодня прямо сейчас */
NSDate *startDate = [NSDate date];
/* И событие заканчивается завтра: 24 часа по 60 минут и 60 секунд в минуте 24 * 60 * 60 */
NSDate *endDate = [startDate dateByAddingTimeInterval:24 * 60 * 60];
/* Создаем новое событие */
BOOL createdSuccessfully = [self createEventWithTitle:@"My event" startDate:startDate endDate:endDate inCalendarWithTitle:@"Calendar" inCalendarWithType:EKCalendarTypeLocal notes:nil];
if (createdSuccessfully){
NSLog(@"Successfully created the event.");
} else {
NSLog(@"Failed to create the event.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Получение содержимого календаря
- (EKCalendar *) calDAVCalendarWithTitleContaining:(NSString *)paramDescription{
EKCalendar *result = nil;
EKEventStore *eventStore = [[EKEventStore alloc] init];
for (EKCalendar *thisCalendar in eventStore.calendars){
if (thisCalendar.type == EKCalendarTypeCalDAV){
if ([thisCalendar.title rangeOfString:paramDescription].location != NSNotFound){
return thisCalendar;
}
}
}
return result;
}
- (void) readEvents{
/* Найти календарь, на котором базируется наш поиск */
EKCalendar *targetCalendar = [self calDAVCalendarWithTitleContaining:@"gmail.com"];
/* Если мы не можем найти CalDAV calendar который мы ищем, тогда мы прерываем операцию */
if (targetCalendar == nil){
NSLog(@"No CalDAV calendars were found.");
return;
}
/* Мы должны передать массив календарей в хранилище событий для поиска */
NSArray *targetCalendars = [[NSArray alloc] initWithObjects:
targetCalendar, nil];
/* Создаем event store */
EKEventStore *eventStore = [[EKEventStore alloc] init];
/* Стартовой датой будет сегодня */
NSDate *startDate = [NSDate date];
/* Конечной датой будет завтра */
NSDate *endDate = [startDate dateByAddingTimeInterval:24 * 60 * 60];
/* Создаем диапазон дат для поиска */
NSPredicate *searchPredicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:targetCalendars];
/* Убеждаемся, что успешно составили диапазон дат */
if (searchPredicate == nil){
NSLog(@"Could not create the search predicate.");
return;
}
/* Получаем все события, которые попали в наш диапазон дат */
NSArray *events = [eventStore eventsMatchingPredicate:searchPredicate];
/* Проходим по всем событиям и выводим информацию из них в консоль */
if (events != nil){
NSUInteger counter = 1;
for (EKEvent *event in events){
NSLog(@"Event %lu Start Date = %@", (unsigned long)counter, event.startDate);
NSLog(@"Event %lu End Date = %@", (unsigned long)counter, event.endDate);
NSLog(@"Event %lu Title = %@", (unsigned long)counter, event.title);
counter++;
}
} else {
NSLog(@"The array of events for this start/end time is nil.");
}
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions{
[self readEvents];
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Удаляем события из календарей
- (BOOL) createEventWithTitle:(NSString *)paramTitle startDate:(NSDate *)paramStartDate endDate:(NSDate *)paramEndDate inCalendarWithTitle:(NSString *)paramCalendarTitle inCalendarWithType:(EKCalendarType)paramCalendarType notes:(NSString *)paramNotes{
BOOL result = NO;
EKEventStore *eventStore = [[EKEventStore alloc] init];
/* Есть ли какие-либо календари доступные в event store? */
if ([eventStore.calendars count] == 0){
NSLog(@"No calendars are found.");
return NO;
}
EKCalendar *targetCalendar = nil;
/* Попробуем найти календарь */
for (EKCalendar *thisCalendar in eventStore.calendars){
if ([thisCalendar.title isEqualToString:paramCalendarTitle] && thisCalendar.type == paramCalendarType){
targetCalendar = thisCalendar;
break;
}
}
/* Убедимся, что мы нашли нужный календарь */
if (targetCalendar == nil){
NSLog(@"Could not find the requested calendar.");
return NO;
}
/* Если календарь не позволяет модифициоровать свое содержимое, тогда мы не можем вставить ничего в него */
if (targetCalendar.allowsContentModifications == NO){
NSLog(@"The selected calendar does not allow modifications.");
return NO;
}
/* Создаем событие */
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.calendar = targetCalendar;
/* Устанавливаем свойство события: title,start date/time, date/time и так далее. */
event.title = paramTitle;
event.notes = paramNotes;
event.startDate = paramStartDate;
event.endDate = paramEndDate;
/* Сохраняем событие в календаре */
NSError *saveError = nil;
result = [eventStore saveEvent:event span:EKSpanThisEvent error:&saveError];
if (result == NO){
NSLog(@"An error occurred = %@", saveError);
}
return result;
}
- (BOOL) removeEventWithTitle:(NSString *)paramTitle startDate:(NSDate *)paramStartDate endDate:(NSDate *)paramEndDate inCalendarWithTitle:(NSString *)paramCalendarTitle inCalendarWithType:(EKCalendarType)paramCalendarType notes:(NSString *)paramNotes{
BOOL result = NO;
EKEventStore *eventStore = [[EKEventStore alloc] init];
/* Есть ли какие-либо календари доступные в event store? */
if ([eventStore.calendars count] == 0){
NSLog(@"No calendars are found.");
return NO;
}
EKCalendar *targetCalendar = nil;
/* Попробуем найти календарь */
for (EKCalendar *thisCalendar in eventStore.calendars){
if ([thisCalendar.title isEqualToString:paramCalendarTitle] &&
thisCalendar.type == paramCalendarType){
targetCalendar = thisCalendar;
break;
}
}
/* Убедимся, что мы нашли нужный календарь */
if (targetCalendar == nil){
NSLog(@"Could not find the requested calendar.");
return NO;
}
/* Если календарь не позволяет модифициоровать свое содержимое, тогда мы не можем вставить ничего в него */
if (targetCalendar.allowsContentModifications == NO){
NSLog(@"The selected calendar does not allow modifications.");
return NO;
}
NSArray *calendars = [[NSArray alloc] initWithObjects:targetCalendar, nil];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:paramStartDate endDate:paramEndDate calendars:calendars];
/* Получить все события, которые соотвествую заданным параметрам */
NSArray *events = [eventStore eventsMatchingPredicate:predicate];
if ([events count] > 0){
/* Удалим их все*/
for (EKEvent *event in events){
NSError *removeError = nil;
/* Не комитьте здесь. Мы сделаем коммит после того, как удалим все элементы. */
if ([eventStore removeEvent:event span:EKSpanThisEvent commit:NO
error:&removeError] == NO){
NSLog(@"Failed to remove event %@ with error = %@", event, removeError);
}
}
NSError *commitError = nil;
if ([eventStore commit:&commitError]){
result = YES;
} else {
NSLog(@"Failed to commit the event store.");
}
} else {
NSLog(@"No events matched your input.");
}
return result;
}
- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSDate *startDate = [NSDate date]; /* Сейчас */
const NSTimeInterval NSOneHour = 60 * 60; /* 60 минут, каждая по 60 секунд */
NSDate *endDate = [startDate dateByAddingTimeInterval:NSOneHour];
BOOL createdSuccessfully = [self createEventWithTitle:@"Shopping" startDate:startDate endDate:endDate inCalendarWithTitle:@"vandad.np@gmail.com" inCalendarWithType:EKCalendarTypeCalDAV notes:@"Get bread"];
if (createdSuccessfully){
NSLog(@"Successfully created the event.");
BOOL removedSuccessfully = [self removeEventWithTitle:@"Shopping" startDate:startDate endDate:endDate inCalendarWithTitle:@"vandad.np@gmail.com"
inCalendarWithType:EKCalendarTypeCalDAV notes:@"Get bread"];
if (removedSuccessfully){
NSLog(@"Successfully removed the event.");
} else {
NSLog(@"Failed to remove the event.");
}
} else {
NSLog(@"Failed to create the event.");
}
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Перечисление и загрузка шрифтов
- (void) enumerateFonts{
for (NSString *familyName in [UIFont familyNames]){
NSLog(@"Font Family = %@", familyName);
}
}
Результат вывода в консоль через NSLog:
Font Family = Heiti TC
Font Family = Sinhala Sangam MN
Font Family = Kannada Sangam MN
Font Family = Georgia
Font Family = Heiti J
Font Family = Times New Roman
Font Family = Snell Roundhand
Font Family = Geeza Pro
Font Family = Helvetica Neue
- (void) enumerateFonts{
for (NSString *familyName in [UIFont familyNames]){
NSLog(@"Font Family = %@", familyName);
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]){
NSLog(@"\t%@", fontName);
}
}
}
Результат вывода в консоль через NSLog:
Font Family = Geeza Pro
GeezaPro
GeezaPro-Bold
Font Family = Helvetica Neue
HelveticaNeue-Italic
HelveticaNeue-Bold
HelveticaNeue-BoldItalic
HelveticaNeue
Отрисовка текста
Файл GraphicsViewControllerView.m
#import "GraphicsViewControllerView.h"
@implementation GraphicsViewControllerView
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// Код инициализации здесь
}
return self;
}
- (void)drawRect:(CGRect)rect{
UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold"
size:40.0f];
NSString *myString = @"Some String";
[myString drawAtPoint:CGPointMake(40, 180) withFont:helveticaBold];
}
@end
Создание, настройка и использование цветов
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
}
- (void)drawRect:(CGRect)rect{
// Код отрисовки
/* Загрузка цвета */
UIColor *magentaColor =[UIColor colorWithRed:0.5f
green:0.0f
blue:0.5f
alpha:1.0f];
/* Установка цвета в графическом контексте */
[magentaColor set];
/* Загрузка шрифта */
UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0f];
/* Текст для отрисовки */
NSString *myString = @"I Learn Really Fast";
/* Отрисовываем строку, используя шрифт. Цвет уже установлен. */
[myString drawAtPoint:CGPointMake(25, 190) withFont:helveticaBold];
}
- (void)drawRect:(CGRect)rect{
// Код отрисовки
/* Загрузка цвета */
UIColor *magentaColor = [UIColor colorWithRed:0.5f
green:0.0f
blue:0.5f
alpha:1.0f];
/* Установка цвета в графическом контексте */
[magentaColor set];
/* Загрузка шрифта */
UIFont *helveticaBold = [UIFont boldSystemFontOfSize:30];
/* Текст для отрисовки */
NSString *myString = @"I Learn Really Fast";
/* Отрисовываем строку, используя шрифт. Цвет уже установлен. */
[myString drawInRect:CGRectMake(100, /* x */
120, /* y */
100, /* ширина */
200) /* высота */
withFont:helveticaBold];
}
Примеры элементов интерфейса iOS UI Elements (iOS UI Element Usage Guidelines):
developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW34
Примеры исходного кода:
examples.oreilly.com/0636920021728
Комментариев нет:
Отправить комментарий