iOS Question How to programmatically connect to a WiFi network given the SSID and password

janderkan

Well-Known Member
Licensed User
Longtime User
This should be the C code:
B4X:
if (@available (iOS 11.0, *)) {
    
    NEHotspotConfiguration * configuration =
                [[NEHotspotConfiguration alloc] initWithSSID: wifiSSID];
    configuration.joinOnce = YES;
    
    /* Alert the OS that the user wants to connect to the WiFi */
    [[NEHotspotConfigurationManager sharedManager]
                      applyConfiguration: configuration
                      completionHandler: ^ (NSError * _Nullable error) {
      if (nil == error) {
        DLog (@ "Is Connected!!");
      } else {
        DLog (@ "Error is:%@", error);
    }}];
}

But I am still lost :)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Example:
B4X:
#ProvisionFile: Push.mobileprovision
#Entitlement: <key>com.apple.developer.networking.HotspotConfiguration</key><true/>

Sub Process_Globals
   Public App As Application
   Public NavControl As NavigationController
   Private Page1 As Page
End Sub

Private Sub Application_Start (Nav As NavigationController)
   NavControl = Nav
   Page1.Initialize("Page1")
   Page1.Title = "Page 1"
   NavControl.ShowPage(Page1)
   ConnectWiFi("xxx", "22323223")
End Sub

Sub ConnectWiFi(SSID As String, Passphrase As String)
   If App.OSVersion < 11 Then Return
   Dim configuration As NativeObject
   configuration = configuration.Initialize("NEHotspotConfiguration").RunMethod("alloc", Null).RunMethod("initWithSSID:passphrase:isWEP:", Array(SSID, Passphrase, False))
   Dim no As NativeObject = Me
   no.RunMethod("ApplyConfiguration:", Array(configuration))
End Sub

#if OBJC
@import NetworkExtension;
- (void)ApplyConfiguration:(NEHotspotConfiguration*) configuration {
       [[NEHotspotConfigurationManager sharedManager]applyConfiguration:configuration completionHandler:^(NSError* error) {
           if (error == nil) {
               NSLog(@"Success");
           }
           else
               NSLog(@"Error: %@", error);
       }
   ];
}
#End If

Make sure to use an explicit app id where the hotspot feature is enabled.
Based on my tests it can report "success" in cases where it didn't really connect (tested with a random ssid).
 
Upvote 0
Top