Ios-quick-guide

提供:Dev Guides
移動先:案内検索

iOS-はじめに

総括

以前はiPhone OSと呼ばれていたiOSは、Apple Inc.が開発したモバイルオペレーティングシステムです。 最初のリリースは2007年で、iPhoneとiPod Touchが含まれていました。 iPad(第1世代)は2010年4月にリリースされ、iPad Miniは2012年11月にリリースされました。

iOSデバイスは非常に頻繁に進化し、経験から、少なくとも1つのバージョンのiPhoneとiPadが毎年発売されることがわかります。 これで、iPhone、iPhone 3gs、iPhone 4、iPhone 4sから先行するiphone5がリリースされました。 同様に、iPadはiPad(1 ^ st ^ Generation)からiPad(4 ^ th ^ Generation)および追加のiPad Miniバージョンに進化しました。

iOS SDKは1.0から6.0に進化しました。 iOS 6.0、最新のSDKは、Xcode 4.5以降で唯一公式にサポートされているバージョンです。 Appleの豊富なドキュメントがあり、展開ターゲットに基づいて使用できるメソッドとライブラリを見つけることができます。 Xcodeの現在のバージョンでは、iOS 4.3、5.0、および6.0の展開ターゲットから選択できます。

iOSの力は、デバイスの一部として提供される以下の機能のいくつかで感じることができます。

  • Maps
  • Siri
  • FacebookとTwitter
  • マルチタッチ
  • 加速度計
  • GPS
  • ハイエンドプロセッサー
  • カメラ
  • サファリ
  • 強力なAPI
  • ゲームセンター
  • アプリ内購入
  • リマインダー
  • 幅広いジェスチャー

iPhone/iPadを使用するユーザーの数は大幅に増加しています。 これは、AppleのApp StoreであるiPhoneおよびiPad用のアプリケーションを作成することにより、開発者が収益を上げる機会を生み出します。

iOSの新しいものの1つとして、AppleはユーザーがiOSデバイス用に開発されたアプリを購入できるアプリケーションストアを設計しました。 開発者は、無料アプリと有料アプリの両方をApp Storeに作成できます。 アプリケーションを開発してストアに配布するには、開発者は、最新のXcodeで開発するために、年間99ドルのiOS開発プログラムとMountain Lion以上のMacに登録する必要があります。

Apple開発者として登録する

Apple IDが最も必要なのは、Appleデバイスを持ち、開発者である場合、間違いなく必要です。 それは無料ですので、持っていても問題はありません。 Appleアカウントを持つことの利点は次のとおりです-

  • 開発ツールへのアクセス。
  • Worldwide Developers Conference(WWDC)ビデオ。
  • 招待されたときにiOS開発者プログラムチームに参加できます。

Appleアカウントを登録するには、以下の手順に従ってください-

  • ステップ1 *-リンクhttps://developer.apple.com/programs/register/をクリックして、「Create Apple ID」を選択します

iOS無料登録

  • ステップ2 *-必要な情報を提供します。これは、ページに記載されているとおりです。
  • ステップ3 *-メール確認でアカウントを確認すると、アカウントがアクティブになります。
  • ステップ4 *-これで、iOSシミュレーターとiOS SDKにパッケージ化されたXcodeなどの開発者ツール、およびその他の開発者リソースをダウンロードできるようになります。

Apple iOS開発者プログラム

新しい開発者に最初に生じる質問は、なぜiOS開発者プログラムに登録する必要があるのですか? 答えは非常に簡単です。 Appleは、常にユーザーに高品質のアプリケーションを提供することに注力しています。 登録料がなかった場合、ジャンクアプリがアップロードされ、Appleのアプリレビューチームに問題を引き起こす可能性があります。

iOS開発者プログラムに参加する利点は次のとおりです-

  • 開発したアプリを実際のiOSデバイスで実行します。
  • アプリをアプリストアに配布します。
  • 開発者のプレビューにアクセスしてください。

iOS開発者プログラムに参加する手順は次のとおりです-

開発者プログラム

  • ステップ2 *-表示されたページで[今すぐ登録]をクリックします。
  • ステップ3 *-既存のAppleアカウントにサインインする(アカウントがある場合)か、新しいApple IDを作成できます。
  • ステップ4 *-その後、個人アカウントと企業アカウントを選択する必要があります。 チームに複数の開発者がいる場合は、会社のアカウントを使用します。 個人アカウントでは、メンバーを追加できません。
  • ステップ5 *-個人情報を入力した後(新しく登録した人向け)、クレジットカードの助けを借りて支払うことでプログラムを購入し、アクティブにすることができます(支払い方法のみ)。
  • ステップ6 *-これで、ページのメンバーセンターオプションを選択して、開発者のリソースにアクセスできるようになります。

メンバーセンター

  • ステップ7 *-ここでは、次のことができるようになります-
  • プロビジョニングプロファイルを作成します。
  • チームとデバイスを管理します。
  • iTunes Connectを介したアプリケーションのアプリストアへの管理。
  • フォーラムと技術サポートを入手してください。

iOS-環境設定

iOS-Xcodeのインストール

Xcodeダウンロード

  • ステップ2 *-Xcode dmgファイルをダブルクリックします。
  • ステップ3 *-デバイスがマウントされ、開かれていることがわかります。
  • ステップ4 *-表示されるウィンドウには、Xcodeアプリケーションとアプリケーションフォルダーのショートカットの2つの項目があります。
  • ステップ5 *-Xcodeをアプリケーションにドラッグすると、アプリケーションにコピーされます。
  • ステップ6 *-これで、選択して実行できる他のアプリケーションの一部としてXcodeが使用可能になります。

また、Mac AppストアからXcodeをダウンロードし、画面に表示されるステップバイステップの手順に従ってインストールする別のオプションもあります。

インターフェースビルダー

インターフェイスビルダーは、UIインターフェイスを簡単に作成できるツールです。 使用するために開発された豊富なUI要素のセットがあります。 UIビューにドラッグアンドドロップするだけです。 今後のページで、UI要素の追加、UI要素のアウトレットとアクションの作成について学習します。

インターフェイスビルダー

必要なUI要素全体で構成されるオブジェクトライブラリが右下にあります。 ユーザーインターフェイスは、多くの場合 xibs と呼ばれ、ファイル拡張子です。 各xibは、対応するView Controllerにリンクされています。

iOSシミュレータ

iOSシミュレータは、実際には2種類のデバイス、つまりiPhoneとiPadの異なるバージョンで構成されています。 iPhoneバージョンには、iPhone(通常)、iPhone Retina、iPhone 5が含まれます。 iPadにはi​​PadとiPad Retinaがあります。 iPhoneシミュレーターのスクリーンショットが下に表示されます。

iPhone Simulator

iOSシミュレーターで位置をシミュレートして、アプリの緯度と経度の効果をいじることができます。 また、シミュレータでメモリ警告と通話中ステータスをシミュレートすることもできます。 ほとんどの目的でシミュレータを使用できますが、加速度計などのデバイス機能をテストすることはできません。 そのため、アプリケーションのすべてのシナリオを徹底的にテストするには、常にiOSデバイスが必要になる場合があります。

iOS-Objective C

iOS開発で使用される言語は客観的Cです。 オブジェクト指向言語であるため、オブジェクト指向プログラミング言語のバックグラウンドを持っている人にとっては簡単です。

インターフェースと実装

Objective Cでは、クラスの宣言が行われるファイルは*インターフェースファイル*と呼ばれ、クラスが定義されるファイルは*実装ファイル*と呼ばれます。

シンプルなインターフェースファイル MyClass.h は次のようになります-

@interface MyClass:NSObject {
  //class variable declared here
}

//class properties declared here
//class methods and instance methods declared here
@end

実装ファイル MyClass.m は次のようになります-

@implementation MyClass
  //class methods defined here
@end

オブジェクト作成

オブジェクトの作成は次のように行われます-

MyClass  *objectName = [[MyClass alloc]init] ;

方法

メソッドは次のようにObjective Cで宣言されています-

-(returnType)methodName:(typeName) variable1 :(typeName)variable2;

例を以下に示します。

-(void)calculateAreaForRectangleWithLength:(CGfloat)length
andBreadth:(CGfloat)breadth;
*andBreadth* 文字列が何のためにあるのか疑問に思うかもしれません。実際にはオプションの文字列であり、特に呼び出し時にメソッドを簡単に読んで理解するのに役立ちます。 同じクラスでこのメソッドを呼び出すには、次のステートメントを使用します-
[self calculateAreaForRectangleWithLength:30 andBreadth:20];

上記のように、andBreadthを使用すると、幅が20であることを理解できます。 Selfは、クラスメソッドであることを指定するために使用されます。

クラスメソッド

クラスのオブジェクトは、クラスのオブジェクトを作成せずに直接アクセスできます。 変数やオブジェクトは関連付けられていません。 例を以下に示します。

+(void)simpleClassMethod;

次のようにクラス名を使用してアクセスできます(クラス名をMyClassと仮定しましょう)-

[MyClass simpleClassMethod];

インスタンスメソッド

インスタンスメソッドは、クラスのオブジェクトを作成した後にのみアクセスできます。 インスタンス変数にメモリが割り当てられます。 インスタンスメソッドの例を以下に示します。

-(void)simpleInstanceMethod;

次のようにクラスのオブジェクトを作成した後にアクセスできます-

MyClass  *objectName = [[MyClass alloc]init] ;
[objectName simpleInstanceMethod];

Objective Cの重要なデータ型

Sr.No. Data Type
1

NSString

文字列を表すために使用されます。

2

CGfloat

浮動小数点値を表すために使用されます(通常のフロートも使用できますが、CGfloatを使用することをお勧めします)。

3

NSInteger

整数を表すために使用されます。

4

BOOL

ブール値を表すために使用されます(YESまたはNOはBOOLタイプが許可されます)。

ログを印刷する

NSLog-ステートメントの印刷に使用されます。 これは、それぞれリリースモードとデバッグモードでデバイスログとデバッグコンソールに出力されます。 例えば、

NSlog(@"");

制御構造

制御構造のほとんどは、inステートメントのようないくつかの追加を除いて、CおよびC ++と同じです。

プロパティ

外部クラスがクラスにアクセスするには、変数プロパティが使用されます。 例えば、

@property(nonatomic , strong) NSString *myString;

プロパティへのアクセス

ドット演算子を使用して、プロパティにアクセスできます。 上記のプロパティにアクセスするには、次のことを行います。

self.myString = @"Test";

また、次のようにsetメソッドを使用することができます-

[self setMyString:@"Test"];

カテゴリー

カテゴリは、既存のクラスにメソッドを追加するために使用されます。 この方法により、実際のクラスが定義されている実装ファイルすら持たないクラスにメソッドを追加できます。 私たちのクラスのサンプルカテゴリは次のとおりです-

@interface MyClass(customAdditions)
- (void)sampleCategoryMethod;
@end

@implementation MyClass(categoryAdditions)

-(void)sampleCategoryMethod {
   NSLog(@"Just a test category");
}

配列

NSMutableArrayとNSArrayは、目的Cで使用される配列クラスです。 名前が示すように、前者は変更可能で、後者は不変です。 例を以下に示します。

NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
[anArray addObject:@"firstobject"];
NSArray *aImmutableArray = [[NSArray alloc]
initWithObjects:@"firstObject",nil];

辞書

NSMutableDictionaryとNSDictionaryは、目的Cで使用される辞書クラスです。 名前が示すように、前者は変更可能で、後者は不変です。 例を以下に示します。

NSMutableDictionary *aMutableDictionary = [[NSMutableArray alloc]init];
[aMutableDictionary setObject:@"firstobject" forKey:@"aKey"];
NSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects:
@"firstObject",nil] forKeys:[ NSArray arrayWithObjects:@"aKey"]];

iOS-最初のiPhoneアプリケーション

最初のアプリの作成

次に、iOSシミュレーターで実行するシンプルなシングルビューアプリケーション(空のアプリ)を作成します。

手順は次のとおりです。

ステップ1 *-Xcodeを開き、 *Create a new Xcode project を選択します。

Xcode Welcomeページ

  • ステップ2 *-*シングルビューアプリケーション*を選択します。

プロジェクトの作成

  • ステップ3 *-製品名、つまり、アプリケーションの名前、組織名、次に会社識別子を入力します。

新規プロジェクト作成オプション

ステップ4 *-範囲外になったときに割り当てられたリソースを自動的に解放するために、 *Use Reference Reference Counting が選択されていることを確認します。 Nextをクリックしてください。

  • ステップ5 *-プロジェクトのディレクトリを選択し、作成を選択します。

プロジェクト選択フォルダーの作成

  • ステップ6 *-次のような画面が表示されます-

Xcodeプロジェクトページ

上の画面で、サポートされている向き、ビルド、リリースの設定を選択できます。 サポートするデバイスバージョンであるフィールド展開ターゲットがあり、4.3を選択できます。これは現在許可されている最小展開ターゲットです。 今のところ、これらは必須ではありません。アプリケーションの実行に焦点を当てましょう。

  • ステップ7 *-次に、Runボタンの近くのドロップダウンでiPhoneシミュレーターを選択し、runを選択します。

image、width = 200、height = 100

  • ステップ8 *-それだけです。最初のアプリケーションが正常に実行されました。 次のように出力が得られます-

image、width = 200、height = 360

次に、インターフェイスビルダーで開始するために、背景色を変更しましょう。 ViewController.xibを選択します。 右側で背景オプションを選択し、色を変更して実行します。

インターフェイスビルダー

上記のプロジェクトでは、デフォルトで、デプロイメントターゲットがiOS 6.0に設定され、自動レイアウトが有効になります。 iOS 4.3以降のデバイスでアプリケーションを実行するために、このアプリケーションの作成の開始時にデプロイメントターゲットをすでに変更していますが、自動レイアウトを無効にしませんでした。

自動レイアウトを無効にするには、各nibのファイルインスペクター、つまりxibファイルの自動レイアウトチェックボックスをオフにする必要があります。 XcodeプロジェクトIDEのさまざまなセクションを次の図に示します(提供:Apple Xcode 4ユーザードキュメント)。

Xcode 4ワークスペース

上記のように、ファイルインスペクタはインスペクタセレクタバーにあり、自動レイアウトはオフにできます。 自動レイアウトは、iOS 6デバイスのみをターゲットにする場合に使用できます。 また、展開ターゲットをiOS 6に上げると、通帳などの多くの新機能を使用できるようになります。 とりあえず、iOS 4.3を展開ターゲットとして使いましょう。

最初のiOSアプリケーションのコード

アプリケーション用に生成された5つの異なるファイルがあります。 それらは次のようにリストされています-

  • AppDelegate.h
  • AppDelegate.m
  • ViewController.h
  • ViewController.m *ViewController.xib

AppDelegate.h

//Header File that provides all UI related items.
#import <UIKit/UIKit.h>

//Forward declaration (Used when class will be defined/imported in future)
@class ViewController;

//Interface for Appdelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate>

//Property window
@property (strong, nonatomic) UIWindow* window;

//Property Viewcontroller

@property (strong, nonatomic) ViewController *viewController;
//this marks end of interface
@end

コードの重要な項目-

  • AppDelegateは、iOSイベントを処理するUIResponderを継承します。
  • UIApplicationDelegateのデリゲートメソッドを実装します。このメソッドは、起動完了、終了間近などの主要なアプリケーションイベントを提供します。
  • iOSデバイス画面のさまざまなビューを管理および調整するUIWindowオブジェクト。 他のすべてのビューがロードされるベースビューのようなものです。 一般に、アプリケーションに対して1つのウィンドウのみがあります。 *画面フローを処理するUIViewController。

AppDelegate.m

//Imports the class Appdelegate's interface
import "AppDelegate.h"

//Imports the viewcontroller to be loaded
#import "ViewController.h"

//Class definition starts here
@implementation AppDelegate


//Method to intimate us that the application launched successfully
- (BOOL)application:(UIApplication* )application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

  //Override point for customization after application launch.
   self.viewController = [[ViewController alloc]
   initWithNibName:@"ViewController" bundle:nil];
   self.window.rootViewController = self.viewController;
   [self.window makeKeyAndVisible];
   return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
  /* Use this method to release shared resources, save user data,
   invalidate timers, and store enough application state information
   to restore your application to its current state in case it is
   terminated later. If your application supports background
   execution, this method is called instead of
   applicationWillTerminate: when the user quits.*/
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
  /* Called as part of the transition from the background to the
   inactive state. Here you can undo many of the changes made on
   entering the background.*/
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  /* Restart any tasks that were paused (or not yet started) while
   the application was inactive. If the application was previously in
   the background, optionally refresh the user interface.*/
}

- (void)applicationWillTerminate:(UIApplication *)application {
  /*Called when the application is about to terminate. Save data if
   appropriate. See also applicationDidEnterBackground:.*/
}

- (void)applicationWillTerminate:(UIApplication *)application {
  /*Called when the application is about to terminate. Save data if appropriate.
   See also applicationDidEnterBackground:.*/
}
@end

コードの重要な項目-

  • UIApplicationデリゲートはここで定義されます。 上記で定義されたすべてのメソッドはUIアプリケーションのデリゲートであり、ユーザー定義のメソッドは含まれていません。
  • UIWindowオブジェクトは、割り当てられたアプリケーションを保持するために割り当てられます。
  • UIViewControllerは、ウィンドウの初期View Controllerとして割り当てられます。
  • ウィンドウを表示するには、makeKeyAndVisibleメソッドが呼び出されます。

ViewController.h

#import <UIKit/UIKit.h>

//Interface for class ViewController
@interface ViewController : UIViewController

@end

コードの重要な項目-

  • ViewControllerクラスは、iOSアプリケーションの基本的なビュー管理モデルを提供するUIViewControllerを継承します。

ViewController.m

#import "ViewController.h"

//Category, an extension of ViewController class
@interface ViewController ()

@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}
@end

コードの重要な項目-

  • ここで実装される2つのメソッドは、基本クラスUIViewControllerで定義されています。
  • ビューのロード後に呼び出されるviewDidLoadで初期セットアップを実行します。
  • didReceiveMemoryWarningメソッドは、メモリ警告の場合に呼び出されます。

iOS-アクションとアウトレット

iOSのアクションとアウトレットは、それぞれ ibActionsibOutlets と呼ばれます。 ib はインターフェイスビルダーを表します。 これらはUI要素に関連しており、それらを実装する方法を視覚的に知ってからそれらを調査します。

アクションとアウトレット–関与するステップ

  • ステップ1 *-最初のiPhoneアプリケーションを使用しましょう。
  • ステップ2 *-ナビゲーターセクションのファイルからViewController.xibファイルを選択します。
  • ステップ3 *-これで、以下に示すウィンドウの右側のライブラリペインからUI要素を選択できます。

iOSチュートリアル

  • ステップ4 *-UIエレメントをインターフェイスビルダーのビューにドラッグアンドドロップできます。
  • ステップ5 *-ビューにLabelとRound Rectボタンを追加しましょう。

iOSチュートリアル

  • ステップ6 *-以下に示すように、右上隅にあるワークスペースツールバーの[エディターセレクター]ボタンから。

iOSチュートリアル

[アシスタントエディター]ボタンを選択します。

iOSチュートリアル

  • ステップ7 *-中央のエディター領域に2つのウィンドウが表示されます。1つはViewController.xibファイルで、もう1つはViewController.hです。
  • ステップ8 *-次に、ラベルを右クリックして、下に示すように新しい参照アウトレットを選択、保持、およびドラッグします。

iOSチュートリアル

  • ステップ9 *-中括弧の間にViewController.hをドロップします。 ファイルに中括弧がない場合は、これを行う前にViewControllerを追加します。 以下に示すようなポップアップが表示されます。

iOSチュートリアル

  • ステップ10 *-アウトレットのラベル名を入力します。ここではラベルmyTitleLabelを使用しています。 [接続]をクリックすると、ibOutletが完了します。
  • ステップ11 *-同様に、アクションを追加するには、Round rectボタンを右クリックし、内部をタッチアップして、中括弧の下にドラッグします。

iOSチュートリアル

  • ステップ12 *-ドロップして、setTitleLabelという名前を付けます。

iOSチュートリアル

  • ステップ13 *-ViewController.mファイルを選択すると、以下に示すようなメソッドが見つかります。
-(IBAction) setTitleLabel:(id)sender {
}
  • ステップ14 *-上記のメソッド内に以下のようにステートメントを追加します。
[myTitleLabel setText:@"Hello"];
  • ステップ15 *-実行ボタンを選択してプログラムを実行します。 次の出力が表示されます。

iOSチュートリアル

  • ステップ16 *-ボタンをクリックします。

iOSチュートリアル

  • ステップ17 *-作成したラベルは、ボタンのアクションによって変更されています。
  • ステップ18 *-上記の例から、IBOutletはUIElement(ここではUILabel)への参照を作成すると結論付けることができます。 同様に、IBActionはUIButtonをメソッドとリンクします。このメソッドは、内部でイベントのタッチアップで呼び出されます。
  • ステップ19 *-アクションの作成中に異なるイベントを選択することで、アクションをいじることができます。

iOS-デリゲート

デリゲートの例

オブジェクトAがオブジェクトBを呼び出してアクションを実行すると仮定します。 アクションが完了すると、オブジェクトAはBがタスクを完了したことを認識し、必要なアクションを実行する必要があります。 これは、デリゲートの助けを借りて達成されます。

上記の例の重要な概念は次のとおりです-

  • AはBのデリゲートオブジェクトです。
  • BはAの参照を持ちます。
  • AはBのデリゲートメソッドを実装します。
  • Bはデリゲートメソッドを通じてAに通知します。

デリゲートを作成する手順

  • ステップ1 *-最初に、単一のビューアプリケーションを作成します。
  • ステップ2 *-次に、ファイル→新規作成→ファイル…​を選択します

iOSチュートリアル

  • ステップ3 *-次にObjective C Classを選択して、[次へ]をクリックします。
  • ステップ4 *-以下に示すように、NSObjectとしてサブクラスを持つSampleProtocolなどのクラスに名前を付けます。

iOSチュートリアル

  • ステップ5 *-次に、作成を選択します。
  • ステップ6 *-プロトコルをSampleProtocol.hファイルに追加すると、更新されたコードは次のようになります-
#import <Foundation/Foundation.h>

//Protocol definition starts here
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end

//Protocol Definition ends here
@interface SampleProtocol : NSObject {
  //Delegate to respond back
   id <SampleProtocolDelegate> _delegate;
}
@property (nonatomic,strong) id delegate;

-(void)startSampleProcess;//Instance method
@end
  • ステップ7 *-以下に示すようにSampleProtocol.mファイルを更新して、インスタンスメソッドを実装します。
#import "SampleProtocol.h"

@implementation SampleProtocol

-(void)startSampleProcess {
   [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate
    selector:@selector(processCompleted) userInfo:nil repeats:NO];
}
@end
  • ステップ8 *-以下に示すように、オブジェクトライブラリからUIViewにラベルをドラッグして、ViewController.xibにUILabelを追加します。

iOSチュートリアル

  • ステップ9 *-ラベルのIBOutletを作成し、myLabelという名前を付け、ViewController.hでSampleProtocolDelegateを採用するために次のようにコードを更新します。
#import <UIKit/UIKit.h>
#import "SampleProtocol.h"

@interface ViewController : UIViewController<SampleProtocolDelegate> {
   IBOutlet UILabel *myLabel;
}
@end
  • ステップ10 *デリゲートメソッドを実装し、SampleProtocolのオブジェクトを作成し、startSampleProcessメソッドを呼び出します。 更新されたViewController.mファイルは次のとおりです-
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];
   sampleProtocol.delegate = self;
   [myLabel setText:@"Processing..."];
   [sampleProtocol startSampleProcess];
  //Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

#pragma mark - Sample protocol delegate
-(void)processCompleted {
   [myLabel setText:@"Process Completed"];
}
@end
  • ステップ11 *次のような出力が表示されます。 最初、ラベルには「処理中…​」が表示されます。これは、デリゲートメソッドがSampleProtocolオブジェクトによって呼び出されると更新されます。

iOSチュートリアル

iOS-UI要素

UI要素とは何ですか?

UI要素は、アプリケーションで見ることができる視覚要素です。 これらの要素には、ボタン、テキストフィールドなどのユーザーインタラクションに応答するものや、画像、ラベルなどの情報を提供するものがあります。

UI要素を追加する方法は?

コードとインターフェイスビルダーの両方を使用して、UI要素を追加できます。 必要に応じて、いずれかを使用できます。

私たちの焦点

アプリケーションのコードを介してUI要素を追加することに焦点を当てます。 インターフェイスビルダーの使用は簡単で簡単です。UI要素をドラッグアンドドロップするだけです。

私たちのアプローチ

単純なiOSアプリケーションを作成し、それを使用してUI要素の一部を説明します。

  • ステップ1 *-最初のiOSアプリケーションで行ったように、Viewbasedアプリケーションを作成します。
  • ステップ2 *-ViewController.hおよびViewController.mファイルのみを更新します。
  • ステップ3 *-次に、UI要素を作成するためのメソッドをViewController.mファイルに追加します。
  • ステップ4 *-viewDidLoadメソッドでこのメソッドを呼び出します。
  • ステップ5 *-コードの重要な行は、それらの行の上に単一行コメントを付けたコードで説明されています。

UI要素のリスト

UI固有の要素とそれらに関連する機能は以下に説明されています-

Sr.No. UI Specific Elements
1

Text Fields

アプリがユーザー入力を取得できるようにするUI要素です。

2

Input types - TextFields

UITextFieldのキーボードプロパティを使用して、ユーザーが提供できる入力の種類を設定できます。

3

Buttons

ユーザーアクションの処理に使用されます。

4

Label

静的コンテンツの表示に使用されます。

5

Toolbar

現在のビューに基づいて何かを操作する場合に使用されます。

6

Status Bar

デバイスのキー情報が表示されます。

7

Navigation Bar

これには、Navigation ControllerのNavigationボタンが含まれています。NavigationControllerは、プッシュおよびポップできるView Controllerのスタックです。

8

Tab bar

通常、同じビュー内のさまざまなサブタスク、ビュー、またはモデルを切り替えるために使用されます。

9

Image View

単純な画像または一連の画像を表示するために使用されます。

10

Scroll View

画面の領域を超えるコンテンツを表示するために使用されます。

11

Table View

複数の行とセクションにデータのスクロール可能なリストを表示するために使用されます。

12

Split View

これは、詳細ペインの情報を制御するマスターペインで2つのペインを表示するために使用されます。

13

Text View

オプションで編集可能なテキスト情報のスクロール可能なリストを表示するために使用されます。

14

View Transition

ビュー間のさまざまなビュー遷移について説明します。

15

Pickers

リストから特定のデータを選択するための表示に使用されます。

16

Switches

アクションの無効化および有効化として使用されます。

17

Sliders

ユーザーが許容値の範囲全体で値またはプロセスを調整できるようにするために使用されます。

18

Alerts

重要な情報をユーザーに提供するために使用されます。

19

Icons

これは、アクションに使用される、またはアプリケーションに関連する何かを描写する画像表現です。

iOS-加速度計

加速度計は、x、y、zの3方向におけるデバイスの位置の変化を検出するために使用されます。 地面に対するデバイスの現在の位置を知ることができます。 この例をテストするには、 device で実行する必要があり、シミュレーターでは動作しません。

加速度計-関与するステップ

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *- *ViewController.xib に3つのラベルを追加し、xlabel、ylabel、zlabelという名前のibOutletsを作成します。

  • ステップ3 *-次のようにViewController.hを更新します-
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIAccelerometerDelegate> {
   IBOutlet UILabel *xlabel;
   IBOutlet UILabel *ylabel;
   IBOutlet UILabel *zlabel;
}
@end

ステップ4 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   [[UIAccelerometer sharedAccelerometer]setDelegate:self];
  //Do any additional setup after loading the view,typically from a nib
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:
   (UIAcceleration *)acceleration {
   [xlabel setText:[NSString stringWithFormat:@"%f",acceleration.x]];
   [ylabel setText:[NSString stringWithFormat:@"%f",acceleration.y]];
   [zlabel setText:[NSString stringWithFormat:@"%f",acceleration.z]];
}
@end

出力

*iPhone* デバイスでアプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

iOS-ユニバーサルアプリケーション

ユニバーサルアプリケーションとは、iPhoneとiPadの両方に対して単一のバイナリで設計されたアプリケーションです。 ユニバーサルアプリケーションにより、コードの再利用と高速更新が可能になります。

ユニバーサルアプリケーション-関与する手順

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *-ファイル名 *ViewController.xib ファイルを、右側のファイルインスペクターで以下に示すように ViewController_iPhone.xib に変更します。

iOSチュートリアル

ステップ3 *-[ファイル]→[新規]→[ファイル…​]を選択します 次に、サブセクション *"User Interface" を選択し、 View を選択します。 Nextをクリックしてください。

iOSチュートリアル

ステップ4 *- *iPad としてデバイスファミリを選択し、[次へ]をクリックします。

iOSチュートリアル

ステップ5 *-ファイルを *ViewController_iPad.xib として保存し、[作成]を選択します。

ステップ6 *- *ViewController_iPhone.xibViewController_iPad.xib の両方の画面中央にラベルを追加します。

ステップ7 *- *ViewController_iPad.xib で、* identityインスペクター*を選択し、カスタムクラスを ViewController として設定します。

iOSチュートリアル

  • ステップ8 *-AppDelegate.mのapplication:DidFinishLaunching:withOptionsメソッドを次のように更新します-
- (BOOL)application:(UIApplication *)application
   didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen
   mainScreen] bounds]];

  //Override point for customization after application launch.
   if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
      self.viewController = [[ViewController alloc]
      initWithNibName:@"ViewController_iPhone" bundle:nil];
   } else {
      self.viewController = [[ViewController alloc] initWithNibName:
      @"ViewController_iPad" bundle:nil];
   }
   self.window.rootViewController = self.viewController;
   [self.window makeKeyAndVisible];
   return YES;
}

ステップ9 *-以下に示すように、プロジェクト概要のデバイスを *Universal に更新します-

iOSチュートリアル

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

iPadシミュレータでアプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

iOS-カメラ管理

カメラは、モバイルデバイスの一般的な機能の1つです。 カメラで写真を撮ってアプリケーションで使用することは可能ですが、それも非常に簡単です。

カメラ管理-関与する手順

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *- *ViewController.xibbutton を追加し、ボタンのIBActionを作成します。

  • ステップ3 *-*画像ビュー*を追加し、imageOutという名前のIBOutletを作成します。

ステップ4 *-次のように *ViewController.h を更新します-

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIImagePickerControllerDelegate> {
   UIImagePickerController *imagePicker;
   IBOutlet UIImageView *imageView;
}

- (IBAction)showCamera:(id)sender;
@end

ステップ5 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

- (IBAction)showCamera:(id)sender {
   imagePicker.allowsEditing = YES;

   if ([UIImagePickerController isSourceTypeAvailable:
   UIImagePickerControllerSourceTypeCamera]) {
      imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
   } else {
      imagePicker.sourceType =
      UIImagePickerControllerSourceTypePhotoLibrary;
   }
   [self presentModalViewController:imagePicker animated:YES];
}

-(void)imagePickerController:(UIImagePickerController *)picker
   didFinishPickingMediaWithInfo:(NSDictionary *)info {
      UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

      if (image == nil) {
         image = [info objectForKey:UIImagePickerControllerOriginalImage];
      }
   imageView.image = image;
}

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

出力

アプリケーションを実行し、カメラの表示ボタンをクリックすると、次の出力が得られます-

iOSチュートリアル

写真を撮ると、写真を編集できます。つまり、以下に示すように移動および拡大縮小できます-

iOSチュートリアル

iOS-ロケーション処理

ユーザーがアプリケーションでコアロケーションフレームワークの助けを借りて情報にアクセスできる場合、iOSでユーザーの現在位置を簡単に見つけることができます。

ロケーション処理-関係する手順

  • ステップ1 *-シンプルなビューベースのアプリケーションを作成します。
  • ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択して、次に示すようにCoreLocation.frameworkを追加します-

iOSチュートリアル

ステップ3 *- *ViewController.xib に2つのラベルを追加し、ラベルにそれぞれ latitudeLabel および longitudeLabel という名前を付けたibOutletsを作成します。

  • ステップ4 *-[ファイル]→[新規]→[ファイル…​]を選択して、新しいファイルを作成します →[Objective C class *]を選択して、[次へ]をクリックします。

ステップ5 *-NSObjectとして *"sub class of" を持つ LocationHandler としてクラスに名前を付けます。

  • ステップ6 *-作成を選択します。

ステップ7 *-次のように *LocationHandler.h を更新します-

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@protocol LocationHandlerDelegate <NSObject>

@required
-(void) didUpdateToLocation:(CLLocation*)newLocation
   fromLocation:(CLLocation*)oldLocation;
@end

@interface LocationHandler : NSObject<CLLocationManagerDelegate> {
   CLLocationManager *locationManager;
}
@property(nonatomic,strong) id<LocationHandlerDelegate> delegate;

+(id)getSharedInstance;
-(void)startUpdating;
-(void) stopUpdating;

@end

ステップ8 *- *LocationHandler.m を次のように更新します-

#import "LocationHandler.h"
static LocationHandler *DefaultManager = nil;

@interface LocationHandler()

-(void)initiate;

@end

@implementation LocationHandler

+(id)getSharedInstance{
   if (!DefaultManager) {
      DefaultManager = [[self allocWithZone:NULL]init];
      [DefaultManager initiate];
   }
   return DefaultManager;
}

-(void)initiate {
   locationManager = [[CLLocationManager alloc]init];
   locationManager.delegate = self;
}

-(void)startUpdating{
   [locationManager startUpdatingLocation];
}

-(void) stopUpdating {
   [locationManager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:
   (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
   if ([self.delegate respondsToSelector:@selector
   (didUpdateToLocation:fromLocation:)]) {
      [self.delegate didUpdateToLocation:oldLocation
      fromLocation:newLocation];
   }
}
@end

ステップ9 *- LocationHandlerデリゲート*を実装し、2つのibOutletsを作成した場合、次のように ViewController.h を更新します-

#import <UIKit/UIKit.h>
#import "LocationHandler.h"

@interface ViewController : UIViewController<LocationHandlerDelegate> {
   IBOutlet UILabel *latitudeLabel;
   IBOutlet UILabel *longitudeLabel;
}
@end

ステップ10 *- *ViewController.m を次のように更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   [[LocationHandler getSharedInstance]setDelegate:self];
   [[LocationHandler getSharedInstance]startUpdating];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(void)didUpdateToLocation:(CLLocation *)newLocation
 fromLocation:(CLLocation *)oldLocation {
   [latitudeLabel setText:[NSString stringWithFormat:
   @"Latitude: %f",newLocation.coordinate.latitude]];
   [longitudeLabel setText:[NSString stringWithFormat:
   @"Longitude: %f",newLocation.coordinate.longitude]];
}
@end

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

iOS-SQLiteデータベース

iOSでSQLiteを使用してデータを処理できます。 sqliteクエリを使用するため、SQLを知っている人にとっては簡単です。

関与するステップ

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択してから、フレームワークの選択で *libsqlite3.dylib ライブラリを追加します。

  • ステップ3 *-[ファイル]→[新規]→[ファイル…​]を選択して、新しいファイルを作成します。 →[Objective C class *]を選択して、[次へ]をクリックします。

ステップ4 *-NSObjectとして *"sub class of" を持つクラスに DBManager として名前を付けます。

  • ステップ5 *-作成を選択します。

ステップ6 *- *DBManager.h を次のように更新します-

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface DBManager : NSObject {
   NSString *databasePath;
}

+(DBManager*)getSharedInstance;
-(BOOL)createDB;
-(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
   department:(NSString*)department year:(NSString*)year;
-(NSArray*) findByRegisterNumber:(NSString*)registerNumber;

@end

ステップ7 *-次のように *DBManager.m を更新します-

#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;

@implementation DBManager

+(DBManager*)getSharedInstance {
   if (!sharedInstance) {
      sharedInstance = [[super allocWithZone:NULL]init];
      [sharedInstance createDB];
   }
   return sharedInstance;
}

-(BOOL)createDB {
   NSString *docsDir;
   NSArray *dirPaths;

  //Get the documents directory
   dirPaths = NSSearchPathForDirectoriesInDomains
   (NSDocumentDirectory, NSUserDomainMask, YES);
   docsDir = dirPaths[0];

  //Build the path to the database file
   databasePath = [[NSString alloc] initWithString:
   [docsDir stringByAppendingPathComponent: @"student.db"]];
   BOOL isSuccess = YES;
   NSFileManager *filemgr = [NSFileManager defaultManager];

   if ([filemgr fileExistsAtPath: databasePath ] == NO) {
      const char *dbpath = [databasePath UTF8String];
      if (sqlite3_open(dbpath, &database) == SQLITE_OK) {
         char *errMsg;
         const char *sql_stmt =
         "create table if not exists studentsDetail (regno integer
         primary key, name text, department text, year text)";

         if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
            isSuccess = NO;
            NSLog(@"Failed to create table");
         }
         sqlite3_close(database);
         return  isSuccess;
      } else {
         isSuccess = NO;
         NSLog(@"Failed to open/create database");
      }
   }
   return isSuccess;
}

- (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
   department:(NSString*)department year:(NSString*)year; {
   const char *dbpath = [databasePath UTF8String];

   if (sqlite3_open(dbpath, &database) == SQLITE_OK) {
      NSString *insertSQL = [NSString stringWithFormat:@"insert into
      studentsDetail (regno,name, department, year) values
      (\"%d\",\"%@\", \"%@\", \"%@\")",[registerNumber integerValue],
      name, department, year];
      const char *insert_stmt = [insertSQL UTF8String];
      sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);

      if (sqlite3_step(statement) == SQLITE_DONE) {
         return YES;
      } else {
         return NO;
      }
      sqlite3_reset(statement);
   }
   return NO;
}

- (NSArray*) findByRegisterNumber:(NSString*)registerNumber {
   const char *dbpath = [databasePath UTF8String];

   if (sqlite3_open(dbpath, &database) == SQLITE_OK) {
      NSString *querySQL = [NSString stringWithFormat:
      @"select name, department, year from studentsDetail where
      regno=\"%@\"",registerNumber];
      const char *query_stmt = [querySQL UTF8String];
      NSMutableArray *resultArray = [[NSMutableArray alloc]init];

      if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
         if (sqlite3_step(statement) == SQLITE_ROW) {
            NSString *name = [[NSString alloc] initWithUTF8String:
            (const char *) sqlite3_column_text(statement, 0)];
            [resultArray addObject:name];

            NSString *department = [[NSString alloc] initWithUTF8String:
            (const char *) sqlite3_column_text(statement, 1)];
            [resultArray addObject:department];

            NSString *year = [[NSString alloc]initWithUTF8String:
            (const char *) sqlite3_column_text(statement, 2)];
            [resultArray addObject:year];
            return resultArray;
         } else {
            NSLog(@"Not found");
            return nil;
         }
         sqlite3_reset(statement);
      }
   }
   return nil;
}

ステップ8 *- *ViewController.xib ファイルを次のように更新します-

iOSチュートリアル

  • ステップ9 *-上記のテキストフィールドのIBOutletsを作成します。
  • ステップ10 *-上記のボタンのIBActionを作成します。

ステップ11 *- *ViewController.h を次のように更新します-

#import <UIKit/UIKit.h>
#import "DBManager.h"

@interface ViewController : UIViewController<UITextFieldDelegate> {
   IBOutlet UITextField *regNoTextField;
   IBOutlet UITextField *nameTextField;
   IBOutlet UITextField *departmentTextField;
   IBOutlet UITextField *yearTextField;
   IBOutlet UITextField *findByRegisterNumberTextField;
   IBOutlet UIScrollView *myScrollView;
}

-(IBAction)saveData:(id)sender;
-(IBAction)findData:(id)sender;
@end

ステップ12 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)
   nibBundleOrNil {
   self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

   if (self) {
     //Custom initialization
   }
   return self;
}

- (void)viewDidLoad {
   [super viewDidLoad];
  //Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(IBAction)saveData:(id)sender {
   BOOL success = NO;
   NSString *alertString = @"Data Insertion failed";

   if (regNoTextField.text.length>0 &&nameTextField.text.length>0 &&
      departmentTextField.text.length>0 &&yearTextField.text.length>0 ) {
      success = [[DBManager getSharedInstance]saveData:
      regNoTextField.text name:nameTextField.text department:
      departmentTextField.text year:yearTextField.text];
   } else {
      alertString = @"Enter all fields";
   }

   if (success == NO) {
      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:
      alertString message:nil
      delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
      [alert show];
   }
}

-(IBAction)findData:(id)sender {
   NSArray *data = [[DBManager getSharedInstance]findByRegisterNumber:
   findByRegisterNumberTextField.text];

   if (data == nil) {
      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:
      @"Data not found" message:nil delegate:nil cancelButtonTitle:
      @"OK" otherButtonTitles:nil];
      [alert show];
      regNoTextField.text = @"";
      nameTextField.text =@"";
      departmentTextField.text = @"";
      yearTextField.text =@"";
   } else {
      regNoTextField.text = findByRegisterNumberTextField.text;
      nameTextField.text =[data objectAtIndex:0];
      departmentTextField.text = [data objectAtIndex:1];
      yearTextField.text =[data objectAtIndex:2];
   }
}

#pragma mark - Text field delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField {
   [myScrollView setFrame:CGRectMake(10, 50, 300, 200)];
   [myScrollView setContentSize:CGSizeMake(300, 350)];
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
   [myScrollView setFrame:CGRectMake(10, 50, 300, 350)];

}

-(BOOL) textFieldShouldReturn:(UITextField *)textField {
   [textField resignFirstResponder];
   return YES;
}
@end

出力

アプリケーションを実行すると、次の出力が得られ、そこで学生の詳細を追加および検索できます-

iOSチュートリアル

iOS-メールの送信

iOSデバイスのメールアプリケーションを使用してメールを送信できます。

関与するステップ

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択してから *MessageUI.framework を追加します。

ステップ3 *- *ViewController.xib にボタンを追加し、電子メールを送信するためのアクションを作成します。

ステップ4 *-次のように *ViewController.h を更新します-

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>

@interface ViewController : UIViewController<MFMailComposeViewControllerDelegate> {
   MFMailComposeViewController *mailComposer;
}

-(IBAction)sendMail:(id)sender;

@end

ステップ5 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(void)sendMail:(id)sender {
   mailComposer = [[MFMailComposeViewController alloc]init];
   mailComposer.mailComposeDelegate = self;
   [mailComposer setSubject:@"Test mail"];
   [mailComposer setMessageBody:@"Testing message
   for the test mail" isHTML:NO];
   [self presentModalViewController:mailComposer animated:YES];
}

#pragma mark - mail compose delegate
-(void)mailComposeController:(MFMailComposeViewController *)controller
   didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{

   if (result) {
      NSLog(@"Result : %d",result);
   }

   if (error) {
      NSLog(@"Error : %@",error);
   }

   [self dismissModalViewControllerAnimated:YES];
}
@end

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

[電子メールの送信]をクリックすると、次の出力が表示されます-

iOSチュートリアル

iOS-オーディオとビデオ

オーディオとビデオは、最新のデバイスでは非常に一般的です。 iOSでは、それぞれ AVFoundation.framework および MediaPlayer.framework を使用してサポートされています。

関与するステップ

ステップ1 *-簡単な Viewベースのアプリケーション*を作成します。

ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択してから、 *AVFoundation.framework および MediaPlayer.framework を追加する必要があります。

  • ステップ3 *-ViewController.xibに2つのボタンを追加し、オーディオとビデオをそれぞれ再生するアクションを作成します。

ステップ4 *-次のように *ViewController.h を更新します-

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController : UIViewController {
   AVAudioPlayer *audioPlayer;
   MPMoviePlayerViewController *moviePlayer;
}
-(IBAction)playAudio:(id)sender;
-(IBAction)playVideo:(id)sender;
@end

ステップ5 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(IBAction)playAudio:(id)sender {
   NSString *path = [[NSBundle mainBundle]
   pathForResource:@"audioTest" ofType:@"mp3"];
   audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
   [NSURL fileURLWithPath:path] error:NULL];
   [audioPlayer play];
}

-(IBAction)playVideo:(id)sender {
   NSString *path = [[NSBundle mainBundle]pathForResource:
   @"videoTest" ofType:@"mov"];
   moviePlayer = [[MPMoviePlayerViewController
   alloc]initWithContentURL:[NSURL fileURLWithPath:path]];
   [self presentModalViewController:moviePlayer animated:NO];
}
@end

Note

期待どおりの出力を得るために、オーディオファイルとビデオファイルを追加する必要があります。

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

ビデオを再生をクリックすると、以下に示すような出力が得られます-

iOSチュートリアル

[音声の再生]をクリックすると、音声が聞こえます。

iOS-ファイル処理

ファイル処理はアプリケーションで視覚的に説明できないため、ファイルの処理に使用される主要な方法を以下に説明します。 アプリケーションバンドルには読み取り権限しかないため、ファイルを変更することはできません。 とにかく、アプリケーションのドキュメントディレクトリを変更できます。

ファイル処理で使用されるメソッド

ファイルの*アクセス*および*操作*に使用される方法については、以下で説明します。 ここでは、FilePath1、FilePath2、およびFilePathの文字列を必要なフルファイルパスに置き換えて、目的のアクションを取得する必要があります。

ファイルがパスに存在するかどうかを確認します

NSFileManager *fileManager = [NSFileManager defaultManager];

//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];

if ([fileManager fileExistsAtPath:@""]==YES) {
   NSLog(@"File exists");
}

2つのファイルの内容の比較

if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
   NSLog(@"Same content");
}

書き込み可能、​​読み取り可能、実行可能かどうかを確認する

if ([fileManager isWritableFileAtPath:@"FilePath"]) {
   NSLog(@"isWritable");
}

if ([fileManager isReadableFileAtPath:@"FilePath"]) {
   NSLog(@"isReadable");
}

if ( [fileManager isExecutableFileAtPath:@"FilePath"]) {
   NSLog(@"is Executable");
}

ファイルを移動

if([fileManager moveItemAtPath:@"FilePath1"
   toPath:@"FilePath2" error:NULL]) {
   NSLog(@"Moved successfully");
}

ファイルをコピー

if ([fileManager copyItemAtPath:@"FilePath1"
   toPath:@"FilePath2"  error:NULL]) {
   NSLog(@"Copied successfully");
}

ファイルを削除

if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
   NSLog(@"Removed successfully");
}

ファイルを読む

NSData *data = [fileManager contentsAtPath:@"Path"];

ファイルを書き込む

[fileManager createFileAtPath:@"" contents:data attributes:nil];

iOS-マップへのアクセス

地図は場所を見つけるのに役立ちます。 マップは、MapKitフレームワークを使用してiOSに統合されています。

関与するステップ

  • ステップ1 *-シンプルなビューベースのアプリケーションを作成します。
  • ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択してからMapKit.frameworkを追加します。
  • ステップ3 *-Corelocation.frameworkも追加する必要があります。
  • ステップ4 *-MapViewをViewController.xibに追加し、ibOutletを作成して、mapViewという名前を付けます。
  • ステップ5 *-[ファイル]→[新規]→[ファイル…​]を選択して、新しいファイルを作成します →Objective Cクラスを選択して、[次へ]をクリックします。
  • ステップ6 *-NSObjectとして「サブクラス」でMapAnnotationとしてクラスに名前を付けます。
  • ステップ7 *-作成を選択します。
  • ステップ8 *-MapAnnotation.hを次のように更新します-
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface MapAnnotation : NSObject<MKAnnotation>
@property (nonatomic, strong) NSString *title;
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;

- (id)initWithTitle:(NSString *)title andCoordinate:
   (CLLocationCoordinate2D)coordinate2d;

@end

ステップ9 *- *MapAnnotation.m を次のように更新します-

#import "MapAnnotation.h"

@implementation MapAnnotation
-(id)initWithTitle:(NSString *)title andCoordinate:
   (CLLocationCoordinate2D)coordinate2d {

   self.title = title;
   self.coordinate =coordinate2d;
   return self;
}
@end

ステップ10 *- *ViewController.h を次のように更新します-

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<MKMapViewDelegate> {
   MKMapView *mapView;
}
@end

ステップ11 *- *ViewController.m を次のように更新します-

#import "ViewController.h"
#import "MapAnnotation.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   mapView = [[MKMapView alloc]initWithFrame:
   CGRectMake(10, 100, 300, 300)];
   mapView.delegate = self;
   mapView.centerCoordinate = CLLocationCoordinate2DMake(37.32, -122.03);
   mapView.mapType = MKMapTypeHybrid;
   CLLocationCoordinate2D location;
   location.latitude = (double) 37.332768;
   location.longitude = (double) -122.030039;

  //Add the annotation to our map view
   MapAnnotation *newAnnotation = [[MapAnnotation alloc]
   initWithTitle:@"Apple Head quaters" andCoordinate:location];
   [mapView addAnnotation:newAnnotation];
   CLLocationCoordinate2D location2;
   location2.latitude = (double) 37.35239;
   location2.longitude = (double) -122.025919;
   MapAnnotation *newAnnotation2 = [[MapAnnotation alloc]
   initWithTitle:@"Test annotation" andCoordinate:location2];
   [mapView addAnnotation:newAnnotation2];
   [self.view addSubview:mapView];
}

//When a map annotation point is added, zoom to it (1500 range)
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views {
   MKAnnotationView *annotationView = [views objectAtIndex:0];
   id <MKAnnotation> mp = [annotationView annotation];
   MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance
   ([mp coordinate], 1500, 1500);
   [mv setRegion:region animated:YES];
   [mv selectAnnotation:mp animated:YES];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}
@end

出力

アプリケーションを実行すると、次のように出力が得られます-

iOSチュートリアル

マップを上にスクロールすると、次のように出力が得られます-

iOSチュートリアル

iOS-アプリ内購入

アプリ内購入は、アプリケーションに関する追加コンテンツの購入や機能のアップグレードに使用されます。

関与するステップ

  • ステップ1 *-iTunes接続で、*一意のアプリID *があり、*バンドルID *を使用してアプリケーションの更新を作成し、対応するプロビジョニングプロファイルを使用してXcodeでコード署名することを確認します。

ステップ2 *-新しいアプリケーションを作成し、アプリケーション情報を更新します。 これについては、Appleの *Add new apps ドキュメンテーションで詳しく知ることができます。

  • ステップ3 *-アプリケーションのページの[アプリ内購入の管理]でアプリ内購入用の新しい製品を追加します。

ステップ4 *-アプリケーションの銀行口座の詳細を設定してください。 これは、 *In-App purchase が機能するようにセットアップする必要があります。 また、アプリのiTunes接続ページの[ユーザーの管理]オプションを使用してテストユーザーアカウントを作成します。

  • ステップ5 *-次のステップは、アプリ内購入用のコードの処理とUIの作成に関連しています。
  • ステップ6 *-*シングルビューアプリケーション*を作成し、バンドル識別子を入力します。これは、iTunes Connectで指定された識別子です。

ステップ7 *-以下に示すように *ViewController.xib を更新します-

iOSチュートリアル

ステップ8 *-3つのラベルと、それぞれproductTitleLabel、productDescriptionLabel、productPriceLabel、purchaseButtonという名前のボタンの *IBOutlets を作成します。

ステップ9 *-プロジェクトファイルを選択し、ターゲットを選択してから *StoreKit.framework を追加します。

ステップ10 *- *ViewController.h を次のように更新します-

#import <UIKit/UIKit.h>
#import <StoreKit/StoreKit.h>

@interface ViewController : UIViewController<
SKProductsRequestDelegate,SKPaymentTransactionObserver> {
   SKProductsRequest *productsRequest;
   NSArray *validProducts;
   UIActivityIndicatorView *activityIndicatorView;
   IBOutlet UILabel *productTitleLabel;
   IBOutlet UILabel *productDescriptionLabel;
   IBOutlet UILabel *productPriceLabel;
   IBOutlet UIButton *purchaseButton;
}

- (void)fetchAvailableProducts;
- (BOOL)canMakePurchases;
- (void)purchaseMyProduct:(SKProduct*)product;
- (IBAction)purchase:(id)sender;

@end

ステップ11 *- *ViewController.m を次のように更新します-

#import "ViewController.h"
#define kTutorialPointProductID
@"com.tutorialPoints.testApp.testProduct"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];

  //Adding activity indicator
   activityIndicatorView = [[UIActivityIndicatorView alloc]
   initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
   activityIndicatorView.center = self.view.center;
   [activityIndicatorView hidesWhenStopped];
   [self.view addSubview:activityIndicatorView];
   [activityIndicatorView startAnimating];

  //Hide purchase button initially
   purchaseButton.hidden = YES;
   [self fetchAvailableProducts];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(void)fetchAvailableProducts {
   NSSet *productIdentifiers = [NSSet
   setWithObjects:kTutorialPointProductID,nil];
   productsRequest = [[SKProductsRequest alloc]
   initWithProductIdentifiers:productIdentifiers];
   productsRequest.delegate = self;
   [productsRequest start];
}

- (BOOL)canMakePurchases {
   return [SKPaymentQueue canMakePayments];
}

- (void)purchaseMyProduct:(SKProduct*)product {
   if ([self canMakePurchases]) {
      SKPayment *payment = [SKPayment paymentWithProduct:product];
      [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
      [[SKPaymentQueue defaultQueue] addPayment:payment];
   } else {
      UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
      @"Purchases are disabled in your device" message:nil delegate:
      self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
      [alertView show];
   }
}
-(IBAction)purchase:(id)sender {
   [self purchaseMyProduct:[validProducts objectAtIndex:0]];
   purchaseButton.enabled = NO;
}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue
updatedTransactions:(NSArray *)transactions {
   for (SKPaymentTransaction *transaction in transactions) {
      switch (transaction.transactionState) {
         case SKPaymentTransactionStatePurchasing:
            NSLog(@"Purchasing");
         break;

         case SKPaymentTransactionStatePurchased:
            if ([transaction.payment.productIdentifier
            isEqualToString:kTutorialPointProductID]) {
               NSLog(@"Purchased ");
               UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
               @"Purchase is completed succesfully" message:nil delegate:
               self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
               [alertView show];
            }
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
         break;

         case SKPaymentTransactionStateRestored:
            NSLog(@"Restored ");
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
         break;

         case SKPaymentTransactionStateFailed:
            NSLog(@"Purchase failed ");
         break
         default:
         break;
      }
   }
}

-(void)productsRequest:(SKProductsRequest *)request
didReceiveResponse:(SKProductsResponse *)response {
   SKProduct *validProduct = nil;
   int count = [response.products count];

   if (count>0) {
      validProducts = response.products;
      validProduct = [response.products objectAtIndex:0];

      if ([validProduct.productIdentifier
         isEqualToString:kTutorialPointProductID]) {
         [productTitleLabel setText:[NSString stringWithFormat:
            @"Product Title: %@",validProduct.localizedTitle]];
         [productDescriptionLabel setText:[NSString stringWithFormat:
            @"Product Desc: %@",validProduct.localizedDescription]];
         [productPriceLabel setText:[NSString stringWithFormat:
            @"Product Price: %@",validProduct.price]];
      }
   } else {
      UIAlertView *tmp = [[UIAlertView alloc]
         initWithTitle:@"Not Available"
         message:@"No products to purchase"
         delegate:self
         cancelButtonTitle:nil
         otherButtonTitles:@"Ok", nil];
         [tmp show];
   }

   [activityIndicatorView stopAnimating];
   purchaseButton.hidden = NO;
}
@end

Note

kTutorialPointProductIDをIn-App Purchase用に作成したproductIDに更新する必要があります。 fetchAvailableProductsのproductIdentifiersのNSSetを更新することにより、複数の製品を追加できます。 同様に、追加する製品IDの購入関連アクションを処理します。

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

設定画面でアカウントからログアウトしていることを確認してください。 Initiate Purchaseをクリックして、Use Existing Apple IDを選択します。 有効なテストアカウントのユーザー名とパスワードを入力します。 数秒後に次のアラートが表示されます。

iOSチュートリアル

製品が正常に購入されると、次のアラートが表示されます。 このアラートを表示するアプリケーション機能を更新するための関連コードを確認できます。

iOSチュートリアル

iOS-iAd統合

iAdは、アップルサーバーによって配信される広告の表示に使用されます。 iAdは、iOSアプリケーションから収益を得るのに役立ちます。

iAd統合-関与するステップ

  • ステップ1 *-シンプルなビューベースのアプリケーションを作成します。
  • ステップ2 *-プロジェクトファイルを選択し、ターゲットを選択して、フレームワークの選択でiAd.frameworkを追加します。
  • ステップ3 *-次のようにViewController.hを更新します-
#import <UIKit/UIKit.h>
#import <iAd/iAd.h>

@interface ViewController : UIViewController<ADBannerViewDelegate> {
   ADBannerView *bannerView;
}
@end

ステップ4 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   bannerView = [[ADBannerView alloc]initWithFrame:
   CGRectMake(0, 0, 320, 50)];

  //Optional to set background color to clear color
   [bannerView setBackgroundColor:[UIColor clearColor]];
   [self.view addSubview: bannerView];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

#pragma mark - AdViewDelegates

-(void)bannerView:(ADBannerView *)banner
   didFailToReceiveAdWithError:(NSError *)error {
   NSLog(@"Error loading");
}

-(void)bannerViewDidLoadAd:(ADBannerView *)banner {
   NSLog(@"Ad loaded");
}

-(void)bannerViewWillLoadAd:(ADBannerView *)banner {
   NSLog(@"Ad will load");
}

-(void)bannerViewActionDidFinish:(ADBannerView *)banner {
   NSLog(@"Ad did finish");
}
@end

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

iOS-GameKit

Gamekitは、iOSアプリケーションにリーダーボード、実績、およびその他の機能を提供するフレームワークです。 このチュートリアルでは、リーダーボードの追加とスコアの更新に必要な手順を説明します。

関与するステップ

  • ステップ1 *-iTunes接続で、*一意のアプリID *があり、*バンドルID *を使用してアプリケーションの更新を作成し、対応するプロビジョニングプロファイルを使用してXcodeでコード署名することを確認します。
  • ステップ2 *-新しいアプリケーションを作成し、アプリケーション情報を更新します。 これについては、apple-addの新しいアプリのドキュメントで詳しく知ることができます。

ステップ3 *-アプリケーションのページの *Manage Game Center でリーダーボードを設定し、単一のリーダーボードを追加して、*リーダーボードID *およびスコアタイプを指定します。 ここでは、finddevguidesとしてリーダーボードIDを提供します。

  • ステップ4 *-次のステップは、コードの処理とアプリケーションのUIの作成に関連しています。

ステップ5 *-*シングルビューアプリケーション*を作成し、*バンドルID *を入力します。これは、 iTunes接続*で指定されたIDです。

  • ステップ6 *-以下に示すようにViewController.xibを更新します-

iOSチュートリアル

ステップ7 *-プロジェクトファイルを選択し、 *targets を選択してから GameKit.framework を追加します。

ステップ8 *-追加したボタンの *IBActions を作成します。

ステップ9 *- *ViewController.h ファイルを次のように更新します-

#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>

@interface ViewController : UIViewController
<GKLeaderboardViewControllerDelegate>

-(IBAction)updateScore:(id)sender;
-(IBAction)showLeaderBoard:(id)sender;

@end

ステップ10 *- *ViewController.m を次のように更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   if([GKLocalPlayer localPlayer].authenticated == NO) {
      [[GKLocalPlayer localPlayer]
      authenticateWithCompletionHandler:^(NSError *error) {
         NSLog(@"Error%@",error);
      }];
   }
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

- (void) updateScore: (int64_t) score
   forLeaderboardID: (NSString*) category {
   GKScore *scoreObj = [[GKScore alloc]
   initWithCategory:category];
   scoreObj.value = score;
   scoreObj.context = 0;

   [scoreObj reportScoreWithCompletionHandler:^(NSError *error) {
     //Completion code can be added here
      UIAlertView *alert = [[UIAlertView alloc]
      initWithTitle:nil message:@"Score Updated Succesfully"
      delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
      [alert show];
   }];
}

-(IBAction)updateScore:(id)sender {
   [self updateScore:200 forLeaderboardID:@"finddevguides"];
}

-(IBAction)showLeaderBoard:(id)sender {
   GKLeaderboardViewController *leaderboardViewController =
   [[GKLeaderboardViewController alloc] init];
   leaderboardViewController.leaderboardDelegate = self;
   [self presentModalViewController:
   leaderboardViewController animated:YES];
}

#pragma mark - Gamekit delegates
- (void)leaderboardViewControllerDidFinish:
(GKLeaderboardViewController *)viewController {
   [self dismissModalViewControllerAnimated:YES];
}
@end

出力

アプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

「リーダーボードを表示」をクリックすると、次のような画面が表示されます-

iOSチュートリアル

「スコアの更新」をクリックすると、スコアがリーダーボードに更新され、以下に示すようなアラートが表示されます-

iOSチュートリアル

iOS-ストーリーボード

ストーリーボードはiOS 5で導入されました。 ストーリーボードを使用する場合、展開ターゲットは5.0以上でなければなりません。 ストーリーボードは、アプリケーションのすべての画面を作成し、1つのインターフェイスMainStoryboard.storyboardで画面を相互接続するのに役立ちます。 また、View Controllerのプッシュ/プレゼンテーションのコーディングを削減するのにも役立ちます。

関与するステップ

  • ステップ1 *-*シングルビューアプリケーション*を作成し、アプリケーションの作成中に必ず*ストーリーボード*チェックボックスを選択してください。

ステップ2 *-シングルビューコントローラを見つけることができる *MainStoryboard.storyboard を選択します。 以下に示すように、View Controllerをもう1つ追加し、View Controllerを更新します。

iOSチュートリアル

  • ステップ3 *-両方のView Controllerを接続しましょう。 「モーダル表示」ボタンを右クリックし、以下に示すように、左側のView Controllerの右側のView Controllerにドラッグします。

iOSチュートリアル

  • ステップ4 *-次のように表示される3つのオプションからモーダルを選択します。

iOSチュートリアル

ステップ5 *-次のように *ViewController.h を更新します-

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

-(IBAction)done:(UIStoryboardSegue *)seque;

@end

ステップ6 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(IBAction)done:(UIStoryboardSegue *)seque {
   [self.navigationController popViewControllerAnimated:YES];
}

@end
  • ステップ7 *-MainStoryboard.storyboardを選択して、右側のView Controllerの[終了]ボタンを右クリックし、[完了]を選択して、下に示すように[戻る]ボタンで接続します。

iOSチュートリアル

出力

*iPhone* デバイスでアプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

「モーダルを表示」を選択すると、次の出力が得られます-

iOSチュートリアル

iOS-自動レイアウト

自動レイアウトは* iOS 6.0で導入されました。自動レイアウトを使用する場合、展開ターゲットは6.0以上である必要があります。 自動レイアウトは、複数の向きと複数のデバイスに使用できるインターフェイスを作成するのに役立ちます。

例の目標

画面の中心から一定の距離に配置される2つのボタンを追加します。 また、ボタンの上から一定の距離から配置されるサイズ変更可能なテキストフィールドを追加しようとします。

私たちのアプローチ

コードにテキストフィールドと2つのボタンを制約とともに追加します。 各UI要素の制約が作成され、スーパービューに追加されます。 目的の結果を得るには、追加する各UI要素の自動サイズ変更を無効にする必要があります。

関与するステップ

  • ステップ1 *-シンプルなビューベースのアプリケーションを作成します。
  • ステップ2 *-ViewController.mのみを編集します。次のとおりです-
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIButton *leftButton;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UITextField *textfield;

@end
@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   UIView *superview = self.view;

  /*1. Create leftButton and add to our view*/
   self.leftButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   self.leftButton.translatesAutoresizingMaskIntoConstraints = NO;
   [self.leftButton setTitle:@"LeftButton" forState:UIControlStateNormal];
   [self.view addSubview:self.leftButton];

  /* 2. Constraint to position LeftButton's X*/
   NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
   constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterX
   relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute:
   NSLayoutAttributeCenterX multiplier:1.0 constant:-60.0f];

  /* 3. Constraint to position LeftButton's Y*/
   NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint
   constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterY
   relatedBy:NSLayoutRelationEqual toItem:superview attribute:
   NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];

  /* 4. Add the constraints to button's superview*/
   [superview addConstraints:@[ leftButtonXConstraint,
   leftButtonYConstraint]];

  /*5. Create rightButton and add to our view*/
   self.rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
   self.rightButton.translatesAutoresizingMaskIntoConstraints = NO;
   [self.rightButton setTitle:@"RightButton" forState:UIControlStateNormal];
   [self.view addSubview:self.rightButton];

  /*6. Constraint to position RightButton's X*/
   NSLayoutConstraint *rightButtonXConstraint = [NSLayoutConstraint
   constraintWithItem:self.rightButton attribute:NSLayoutAttributeCenterX
   relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute:
   NSLayoutAttributeCenterX multiplier:1.0 constant:60.0f];

  /*7. Constraint to position RightButton's Y*/
   rightButtonXConstraint.priority = UILayoutPriorityDefaultHigh;
   NSLayoutConstraint *centerYMyConstraint = [NSLayoutConstraint
   constraintWithItem:self.rightButton attribute:NSLayoutAttributeCenterY
   relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute:
   NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];
   [superview addConstraints:@[centerYMyConstraint,
   rightButtonXConstraint]];

  //8. Add Text field
   self.textfield = [[UITextField alloc]initWithFrame:
   CGRectMake(0, 100, 100, 30)];
   self.textfield.borderStyle = UITextBorderStyleRoundedRect;
   self.textfield.translatesAutoresizingMaskIntoConstraints = NO;
   [self.view addSubview:self.textfield];

  //9. Text field Constraints
   NSLayoutConstraint *textFieldTopConstraint = [NSLayoutConstraint
   constraintWithItem:self.textfield attribute:NSLayoutAttributeTop
   relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview
   attribute:NSLayoutAttributeTop multiplier:1.0 constant:60.0f];
   NSLayoutConstraint *textFieldBottomConstraint = [NSLayoutConstraint
   constraintWithItem:self.textfield attribute:NSLayoutAttributeTop
   relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self.rightButton
   attribute:NSLayoutAttributeTop multiplier:0.8 constant:-60.0f];
   NSLayoutConstraint *textFieldLeftConstraint = [NSLayoutConstraint
   constraintWithItem:self.textfield attribute:NSLayoutAttributeLeft
   relatedBy:NSLayoutRelationEqual toItem:superview attribute:
   NSLayoutAttributeLeft multiplier:1.0 constant:30.0f];
   NSLayoutConstraint *textFieldRightConstraint = [NSLayoutConstraint
   constraintWithItem:self.textfield attribute:NSLayoutAttributeRight
   relatedBy:NSLayoutRelationEqual toItem:superview attribute:
   NSLayoutAttributeRight multiplier:1.0 constant:-30.0f];
   [superview addConstraints:@[textFieldBottomConstraint ,
   textFieldLeftConstraint, textFieldRightConstraint,
   textFieldTopConstraint]];
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}
@end

注意点

1、5、および8とマークされた手順では、プログラムで2つのボタンとテキストフィールドをそれぞれ追加しました。

残りの手順では、制約を作成し、それらの制約をそれぞれのスーパービュー(実際には自己ビュー)に追加しました。 左ボタンのいずれかの制約は以下に示すとおりです-

NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint
constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute:
NSLayoutAttributeCenterX multiplier:1.0 constant:-60.0f];

constraintWithItemおよびtoItemを使用して、どのUI要素から制約を作成するかを決定します。 この属性は、2つの要素をどの基準でリンクするかを決定します。 「relatedBy」は、属性が要素間でどの程度の効果を持つかを決定します。 Multiplierは乗算係数であり、定数が乗算器に追加されます。

上記の例では、leftButtonのXは、スーパービューの中心に対して常に-60ピクセル以上です。 同様に、他の制約が定義されています。

出力

アプリケーションを実行すると、iPhoneシミュレーターで次の出力が得られます-

iOSチュートリアル

シミュレータの向きを横向きに変更すると、次の出力が得られます-

iOSチュートリアル

iPhone 5シミュレータで同じアプリケーションを実行すると、次の出力が得られます-

iOSチュートリアル

シミュレータの向きを横向きに変更すると、次の出力が得られます-

iOSチュートリアル

iOS-TwitterおよびFacebook

Twitterは iOS 5.0 に統合され、Facebookは iOS 6.0 に統合されました。 このチュートリアルでは、Appleが提供するクラスの使用に焦点を当てており、TwitterとFacebookの展開ターゲットはそれぞれiOS 5.0とiOS 6.0です。

関与するステップ

  • ステップ1 *-シンプルなビューベースのアプリケーションを作成します。

ステップ2 *-プロジェクトファイルを選択してから、 *targets を選択し、 Social.framewor * kおよび Accounts.frameworkchoose frameworks に追加します。

  • ステップ3 *-facebookPostとtwitterPostという名前の2つのボタンを追加し、それらのibActionsを作成します。

ステップ4 *-次のように *ViewController.h を更新します-

#import <Social/Social.h>
#import <Accounts/Accounts.h>
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

-(IBAction)twitterPost:(id)sender;
-(IBAction)facebookPost:(id)sender;

@end

ステップ5 *-次のように *ViewController.m を更新します-

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

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

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
  //Dispose of any resources that can be recreated.
}

-(IBAction)facebookPost:(id)sender {
   SLComposeViewController *controller = [SLComposeViewController
   composeViewControllerForServiceType:SLServiceTypeFacebook];
   SLComposeViewControllerCompletionHandler myBlock =
      ^(SLComposeViewControllerResult result){

      if (result == SLComposeViewControllerResultCancelled) {
         NSLog(@"Cancelled");
      } else {
         NSLog(@"Done");
      }
      [controller dismissViewControllerAnimated:YES completion:nil];
   };
   controller.completionHandler = myBlock;

  //Adding the Text to the facebook post value from iOS
   [controller setInitialText:@"My test post"];

  //Adding the URL to the facebook post value from iOS
   [controller addURL:[NSURL URLWithString:@"http://www.test.com"]];

  //Adding the Text to the facebook post value from iOS
   [self presentViewController:controller animated:YES completion:nil];
}

-(IBAction)twitterPost:(id)sender {
   SLComposeViewController *tweetSheet = [SLComposeViewController
   composeViewControllerForServiceType:SLServiceTypeTwitter];
   [tweetSheet setInitialText:@"My test tweet"];
   [self presentModalViewController:tweetSheet animated:YES];
}
@end

出力

アプリケーションを実行してfacebookPostをクリックすると、次の出力が得られます-

iOSチュートリアル

twitterPostをクリックすると、次の出力が得られます-

iOSチュートリアル

iOS-メモリ管理

iOSのメモリ管理は、当初、オブジェクトを保持および解放する必要がある非ARC(自動参照カウント)でした。 現在、ARCをサポートしており、オブジェクトを保持および解放する必要はありません。 Xcodeはコンパイル時に自動的にジョブを処理します。

メモリ管理の問題

Appleのドキュメントによると、メモリ管理の2つの主要な問題は次のとおりです-

  • まだ使用中のデータを解放または上書きします。 メモリの破損を引き起こし、通常、アプリケーションがクラッシュしたり、さらに悪いことにユーザーデータが破損したりします。
  • 使用されなくなったデータを解放しないと、メモリリークが発生します。 割り当てられたメモリが再び使用されることはないにもかかわらず解放されない場合、メモリリークと呼ばれます。 リークにより、アプリケーションは増え続けるメモリ量を使用し、その結果、システムパフォーマンスが低下したり(iOSで)アプリケーションが終了したりする可能性があります。

メモリ管理ルール

  • 私たちは作成したオブジェクトを所有しており、それらが不要になったらそれらを解放する必要があります。
  • Retainを使用して、作成しなかったオブジェクトの所有権を取得します。 これらのオブジェクトは、不要なときにも解放する必要があります。
  • 自分が所有していないオブジェクトをリリースしないでください。

ARCでのメモリの処理

リリースを使用してARCで保持する必要はありません。 そのため、View Controllerが削除されると、View Controllerのすべてのオブジェクトが解放されます。 同様に、オブジェクトのサブオブジェクトは、リリースされるとリリースされます。 他のクラスがクラスのオブジェクトへの強い参照を持っている場合、クラス全体は解放されないことに注意してください。 そのため、デリゲートには弱いプロパティを使用することをお勧めします。

メモリ管理ツール

Xcodeツールインストゥルメントの助けを借りて、メモリの使用量を分析できます。 アクティビティモニター、割り当て、リーク、ゾンビなどのツールが含まれています。

メモリ割り当てを分析する手順

  • ステップ1 *-既存のアプリケーションを開きます。
  • ステップ2 *-製品を選択し、次に示すようにプロファイルを選択します。

iOSチュートリアル

  • ステップ3 *-次の画面で[割り当て]を選択し、[プロファイル]を選択します。

iOSチュートリアル

  • ステップ4 *-以下に示すように、さまざまなオブジェクトのメモリの割り当てが表示されます。
  • ステップ5 *-View Controllerを切り替えて、メモリが適切に解放されているかどうかを確認できます。

iOSチュートリアル

  • ステップ6 *-同様に、Allocationsの代わりに、Activity Monitorを使用して、アプリケーションに割り当てられたメモリ全体を確認できます。

iOSチュートリアル

  • ステップ7 *-これらのツールは、メモリ消費量にアクセスし、潜在的なリークが発生した場所を特定するのに役立ちます。

iOS-アプリケーションのデバッグ

アプリケーションの開発中にミスを犯す可能性があり、さまざまな種類のエラーにつながる可能性があります。 これらのエラーまたはバグを修正するには、アプリケーションをデバッグする必要があります。

デバッガーの選択

Xcodeには、GDBデバッガーとLLDBデバッガーの2つのデバッガーがあります。 GDBはデフォルトで選択されています。 LLDBは、LLVMオープンソースコンパイラプロジェクトの一部であるデバッガです。 「アクティブなスキームを編集」オプションでデバッガーを変更できます。

コーディングエラーを見つける方法

コーディング関連のエラーを見つけるには、コードをコンパイルするアプリケーションをビルドする必要があります。 コードにエラーが含まれる場合、コンパイラーはすべてのメッセージ、エラー、警告を考えられる理由とともに表示します。

[製品]をクリックしてから[分析]をクリックすると、アプリケーションで発生する可能性のある問題を見つけることができます。

ブレークポイントを設定する

ブレークポイントは、アプリケーションオブジェクトのさまざまな状態を知るのに役立ち、論理的な問題を含む多くの欠陥を識別するのに役立ちます。 ブレークポイントを作成するには、行番号をクリックするだけです。 ブレークポイントを削除するには、クリックしてドラッグするだけです。 次のスクリーンショットは、ブレークポイントを設定する方法を示しています-

iOSチュートリアル

アプリケーションを実行してplayVideoボタンを選択すると、アプリケーションはブレークポイントを設定した行番号で一時停止します。 これにより、アプリケーションの状態を分析する時間ができます。 ブレークポイントがトリガーされると、以下に示すような出力が得られます。

iOSチュートリアル

どのスレッドがブレークポイントをトリガーしたかを簡単に識別できます。 下部には、対応するオブジェクトの値を保持するself、senderなどのオブジェクトが表示され、これらのオブジェクトの一部を展開して、これらの各オブジェクトの状態を確認できます。

アプリケーションを続行するには、以下に示すデバッグ領域で、続行ボタン(左端のボタン)を選択します。 他のオプションには、ステップイン、ステップアウト、ステップオーバーが含まれます。

iOSチュートリアル

例外ブレークポイント

また、例外が発生した場所でアプリケーションを停止させるトリガーブレークポイントもあります。 デバッグナビゲーターを選択した後、+ボタンを選択して、例外ブレークポイントを挿入できます。 次のウィンドウが表示されます。

iOSチュートリアル

次に、[例外ブレークポイントの追加]を選択する必要があります。これにより、次のウィンドウが表示されます。

iOSチュートリアル

デバッグおよびその他のXcode機能に関する詳細情報は、https://developer.apple.com/xcode/[Xcode 4ユーザーガイド]から収集できます。