LoginSignup
9
1

More than 5 years have passed since last update.

FlutterでのiOS API呼び出し

Last updated at Posted at 2018-04-11

Flutter7日目。

iOS連携

iOS側の機能を呼び出す際には Dart と Objective-C もしくは Swift と連携をする必要がある。
Flutterではチャンネルのキーワードを決めることで必要な連絡を取れるようになっている。

今回はその中でも Dart から連絡を入れる場合。
とはいえ結局は6日目にあげたリンク
Writing custom platform-specific code with platform channels
の実際どうするの?話に尽きる。

チャンネルとは?

要は文字列。

Dart では

const MethodChannel('samples.flutter.io/battery');

と書いてあるもの。

Objective-C では

methodChannelWithName:@"samples.flutter.io/battery"

文字列が同じ。

関数の呼び出し方

つまりは Dart 側。

MethodChannel methodChannel;
final int result = await methodChannel.invokeMethod('getBatteryLevel', ['Hello', 'World']);

これで引数が渡せる。

引数の取り方

Objective-C の場合

引数無しは上記リンクで。
引数有りの場合

NSArray* arguments = call.arguments;
NSString* word = arguments[0];

ってやると引数に渡した文字列が取れる。
int を渡したなら int で受け取りましょう。

Swift の場合

let arguments = call.arguments as! Array<Any>;
let word = arguments[0] as! String;

で受け取りましょう。
Swiftでargumentsの定義にとんでも id がどうこうと見えるだけで結局どうしたらよいかわからんかった。

おまけ

id とは?
Objective-C にある型で、C でいう void* のようなものっぽい。
Swiftではこれが Any となるっぽい。as! や as? に関しては Swift のキャストについて調べてみてね。

この内容は
個人ブログ でも投稿されております。


お仕事募集しております
株式会社xhift

北千住でコワーキングスペースも運営しておりました。再開したい!
Bono Prince(ぼのプリ)


9
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
1