Reputation: 368
I am working with IOT weather connect display(Use Local Network) that connect with the router using iOS app. connection between display and iOS app is done by local network.popup came up at the time of connection for allowing the local network privacy but i want to check in advance that user has allowed or not local network permission. I refer this iOS 14 How to trigger Local Network dialog and check user answer? and https://developer.apple.com/forums/thread/663858 but i am looking for code in Objecitve-C. please help me with that
Upvotes: 2
Views: 4700
Reputation: 13758
This is my original answer that is written in Swift - iOS 14 How to trigger Local Network dialog and check user answer? and you can use it from objc as well without any effort.
But if you have a pure ObjC project and don't want to add swift files this is the similar approach that works the same:
// LocalNetworkPrivacy.h
@interface LocalNetworkPrivacy : NSObject
- (void)checkAccessState:(void (^)(BOOL))completion;
@end
// LocalNetworkPrivacy.m
#import <UIKit/UIKit.h>
#import "LocalNetworkPrivacy.h"
@interface LocalNetworkPrivacy () <NSNetServiceDelegate>
@property (nonatomic) NSNetService *service;
@property (nonatomic) void (^completion)(BOOL);
@property (nonatomic) NSTimer *timer;
@property (nonatomic) BOOL publishing;
@end
@implementation LocalNetworkPrivacy
- (instancetype)init {
if (self = [super init]) {
self.service = [[NSNetService alloc] initWithDomain:@"local." type:@"_lnp._tcp." name:@"LocalNetworkPrivacy" port:1100];
}
return self;
}
- (void)dealloc {
[self.service stop];
}
- (void)checkAccessState:(void (^)(BOOL))completion {
self.completion = completion;
self.timer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:YES block:^(NSTimer * _Nonnull timer) {
if (UIApplication.sharedApplication.applicationState != UIApplicationStateActive) {
return;
}
if (self.publishing) {
[self.timer invalidate];
self.completion(NO);
}
else {
self.publishing = YES;
self.service.delegate = self;
[self.service publish];
}
}];
}
#pragma mark - NSNetServiceDelegate
- (void)netServiceDidPublish:(NSNetService *)sender {
[self.timer invalidate];
self.completion(YES);
}
@end
How to use:
LocalNetworkPrivacy* localNetworkPrivacy = [LocalNetworkPrivacy new];
[localNetworkPrivacy checkAccessState:^(BOOL granted) {
NSLog(@"Granted: %@", granted ? @"YES" : @"NO");
}];
NOTE: You must set
NSLocalNetworkUsageDescription
and add "_lnp._tcp." toNSBonjourServices
into your Info.plist.
Upvotes: 4