본문 바로가기
프로그래밍/Flutter-Dart

[Flutter] wifi connect 정보

by 채연2 2021. 3. 22.

 

 

 

* IOS 13이상부터는 getWifiBSSID()와 getWifiName() 함수는 null로 반환된다고 한다.

알 수 있는 정보는.. 어디에 연결되어있는지와 ip뿐이다..ㅜㅜ

 

pubspec.yaml

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  wifi_info_flutter_platform_interface:
  connectivity:

 

320x100

 

utils/wifi.dart

import 'dart:async';

import 'package:flutter/services.dart';
import 'package:wifi_info_flutter_platform_interface/wifi_info_flutter_platform_interface.dart';

export 'package:wifi_info_flutter_platform_interface/wifi_info_flutter_platform_interface.dart'
    show LocationAuthorizationStatus;

/// Checks WI-FI status and more.
class WifiInfo {
  WifiInfo._();

  factory WifiInfo() => _singleton;

  static final WifiInfo _singleton = WifiInfo._();

  static WifiInfoFlutterPlatform get _platform =>
      WifiInfoFlutterPlatform.instance;

  Future<String?> getWifiName() {
    return _platform.getWifiName();
  }

  Future<String?> getWifiBSSID() {
    return _platform.getWifiBSSID();
  }

  Future<String?> getWifiIP() {
    return _platform.getWifiIP();
  }

  Future<LocationAuthorizationStatus> requestLocationServiceAuthorization({
    bool requestAlwaysLocationUsage = false,
  }) {
    return _platform.requestLocationServiceAuthorization(
      requestAlwaysLocationUsage: requestAlwaysLocationUsage,
    );
  }

  Future<LocationAuthorizationStatus> getLocationServiceAuthorization() {
    return _platform.getLocationServiceAuthorization();
  }
}

 

 

 

main.dart

// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:io';

import 'package:connectivity/connectivity.dart'
    show Connectivity, ConnectivityResult;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/utils/wifi.dart';

// Sets a platform override for desktop to avoid exceptions. See
// https://flutter.dev/desktop#target-platform-override for more info.
void _enablePlatformOverrideForDesktop() {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux)) {
    debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
  }
}

void main() {
  _enablePlatformOverrideForDesktop();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _connectionStatus = 'Unknown';
  final Connectivity _connectivity = Connectivity();
  final WifiInfo _wifiInfo = WifiInfo();
  late StreamSubscription<ConnectivityResult> _connectivitySubscription;

  @override
  void initState() {
    super.initState();
    initConnectivity();
    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initConnectivity() async {
    late ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return Future.value(null);
    }

    return _updateConnectionStatus(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Connectivity example app'),
      ),
      body: Center(child: Text('Connection Status: $_connectionStatus')),
    );
  }

  Future<void> _updateConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
        String? wifiName, wifiBSSID, wifiIP;

        try {
          if (!kIsWeb && Platform.isIOS) {
            LocationAuthorizationStatus status =
            await _wifiInfo.getLocationServiceAuthorization();
            if (status == LocationAuthorizationStatus.notDetermined) {
              status = await _wifiInfo.requestLocationServiceAuthorization();
            }
            if (status == LocationAuthorizationStatus.authorizedAlways ||
                status == LocationAuthorizationStatus.authorizedWhenInUse) {
              wifiName = await _wifiInfo.getWifiName();
            } else {
              wifiName = await _wifiInfo.getWifiName();
            }
          } else {
            wifiName = await _wifiInfo.getWifiName();
          }
        } on PlatformException catch (e) {
          print(e.toString());
          wifiName = "Failed to get Wifi Name";
        }

        try {
          if (!kIsWeb && Platform.isIOS) {
            LocationAuthorizationStatus status =
            await _wifiInfo.getLocationServiceAuthorization();
            if (status == LocationAuthorizationStatus.notDetermined) {
              status = await _wifiInfo.requestLocationServiceAuthorization();
            }
            if (status == LocationAuthorizationStatus.authorizedAlways ||
                status == LocationAuthorizationStatus.authorizedWhenInUse) {
              wifiBSSID = await _wifiInfo.getWifiBSSID();
            } else {
              wifiBSSID = await _wifiInfo.getWifiBSSID();
            }
          } else {
            wifiBSSID = await _wifiInfo.getWifiBSSID();
          }
        } on PlatformException catch (e) {
          print(e.toString());
          wifiBSSID = "Failed to get Wifi BSSID";
        }

        try {
          wifiIP = await _wifiInfo.getWifiIP();
        } on PlatformException catch (e) {
          print(e.toString());
          wifiIP = "Failed to get Wifi IP";
        }

        setState(() {
          _connectionStatus = '$result\n'
              'Wifi Name: $wifiName\n'
              'Wifi BSSID: $wifiBSSID\n'
              'Wifi IP: $wifiIP\n';
        });
        break;
      case ConnectivityResult.mobile:
      case ConnectivityResult.none:
        setState(() => _connectionStatus = result.toString());
        break;
      default:
        setState(() => _connectionStatus = 'Failed to get connectivity.');
        break;
    }
  }
}

 

 

 

※ ios/Runner/Info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Gather location updates to get SSID information</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Gather location updates to get SSID information</string>
<key>com.apple.developer.networking.wifi-info</key>
<true/>

 

 

 

 

다음과 같이 해서 빌드하면 정보를 알 수 있다!

 

 

 

 

+ wifi 정보를 얻어오려면 apple developer 등록을 해줘야한다고 한다. 등록 후에 Access wifi information을 활성화 시켜주면.. 되려나?

 

 

 

 

참고 : github.com/flutter/plugins/tree/master/packages/wifi_info_flutter/wifi_info_flutter

 

flutter/plugins

Plugins for Flutter maintained by the Flutter team - flutter/plugins

github.com

 

320x100

'프로그래밍 > Flutter-Dart' 카테고리의 다른 글

[Flutter] Image Picker  (2) 2021.03.23
[Flutter] Login App (1)  (0) 2021.03.23
[Flutter] Webview JavaScript Handler 등록  (0) 2021.03.22
[Flutter] WebView JS 통신  (2) 2021.03.19
[Flutter] IOS 앱 구동 (2)  (0) 2021.03.19

댓글