I've done as the guide says
This is the message manager
[GNSMessageManager setDebugLoggingEnabled:YES];
messageManager = [[GNSMessageManager alloc] initWithAPIKey:API_KEY paramsBlock:^(GNSMessageManagerParams *params) {
params.bluetoothPowerErrorHandler = ^(BOOL hasError) {
// Update the UI for Bluetooth power
};
params.bluetoothPermissionErrorHandler = ^(BOOL hasError) {
// Update the UI for Bluetooth permission
};
}];
These are my methods to publish and subscribe with the Nearby API.
- (IBAction)onPublish:(id)sender {
NSLog(#"publish");
NSString* str = #"hello world";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
GNSMessage* message = [GNSMessage messageWithContent:data];
id<GNSPublication> publication = [messageManager publicationWithMessage:message paramsBlock:^(GNSPublicationParams *publicationParams) {
publicationParams.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams * strategyParams) {
strategyParams.allowInBackground = YES;
strategyParams.discoveryMediums = kGNSDiscoveryMediumsBLE;
strategyParams.discoveryMode = kGNSDiscoveryModeDefault;
}];;
}];
}
- (IBAction)onSubscribe:(id)sender {
NSLog(#"subscribe");
id<GNSSubscription> subscription = [messageManager subscriptionWithMessageFoundHandler:^(GNSMessage *msg) {
// Add the name to a list for display
NSLog(#"message found %#", [msg description]);
} messageLostHandler:^(GNSMessage *msg) {
// Add the name to a list for display
NSLog(#"message lost %#", [msg description]);
} paramsBlock:^(GNSSubscriptionParams *subscriptionParams) {
subscriptionParams.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams * strategyParams) {
strategyParams.allowInBackground = YES;
strategyParams.discoveryMediums = kGNSDiscoveryMediumsBLE;
strategyParams.discoveryMode = kGNSDiscoveryModeDefault;
}];;
}];
}
Both Bletooth central and peripheral background capabilities are enabled, and the permission string for the peripheral is set.
Finally I subscribe on an iOS device and publish from another one but nothing happens.
Be sure to retain the publication and subscription objects. They stop publishing/subscribing when they're deallocated. The usual way is to store them as properties/ivars in one of your classes.
The developer docs are misleading on this point, and I apologize. We'll improve the docs in the next release.
I am working on an existing objective c project , While reading Address Book UI Framework Reference for iOS i found the below classes have deprecated in iOS 9 .
( ABUnknownPersonViewController , ABPersonViewController , ABPeoplePickerNavigationController, ABNewPersonViewController )
What is the replacement of this .? Where i can find some document related this . any help appreciated . Thanks in advance .
The AddressBookUI framework has been deprecated in iOS 9, so better you should use ContactsUI Framework.
It has many new features including all the features of AddressBookUI framework.
So, in case if you are targeting the iOS 9 specifically then you should go for ContactsUI Framework.
To check that AddressBookUI framework is available for specific iOS version you can do the following:
if ([CNContactStore class]) {
CNContactStore *store = [CNContactStore new];
//...
} else {
// Fallback to old framework
}
Here is the complete code for that:
- (void) contactScan
{
if ([CNContactStore class]) {
//ios9 or later
CNEntityType entityType = CNEntityTypeContacts;
if( [CNContactStore authorizationStatusForEntityType:entityType] == CNAuthorizationStatusNotDetermined)
{
CNContactStore * contactStore = [[CNContactStore alloc] init];
[contactStore requestAccessForEntityType:entityType completionHandler:^(BOOL granted, NSError * _Nullable error) {
if(granted){
[self getAllContact];
}
}];
}
else if( [CNContactStore authorizationStatusForEntityType:entityType]== CNAuthorizationStatusAuthorized)
{
[self getAllContact];
}
}
}
-(void)getAllContact
{
if([CNContactStore class])
{
//iOS 9 or later
NSError* contactError;
CNContactStore* addressBook = [[CNContactStore alloc]init];
[addressBook containersMatchingPredicate:[CNContainer predicateForContainersWithIdentifiers: #[addressBook.defaultContainerIdentifier]] error:&contactError];
NSArray * keysToFetch =#[CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPostalAddressesKey];
CNContactFetchRequest * request = [[CNContactFetchRequest alloc]initWithKeysToFetch:keysToFetch];
BOOL success = [addressBook enumerateContactsWithFetchRequest:request error:&contactError usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop){
[self parseContactWithContact:contact];
}];
}
}
- (void)parseContactWithContact :(CNContact* )contact
{
NSString * firstName = contact.givenName;
NSString * lastName = contact.familyName;
NSString * phone = [[contact.phoneNumbers valueForKey:#"value"] valueForKey:#"digits"];
NSStrubg * email = [contact.emailAddresses valueForKey:#"value"];
NSArray * addrArr = [self parseAddressWithContac:contact];
}
- (NSMutableArray *)parseAddressWithContac: (CNContact *)contact
{
NSMutableArray * addrArr = [[NSMutableArray alloc]init];
CNPostalAddressFormatter * formatter = [[CNPostalAddressFormatter alloc]init];
NSArray * addresses = (NSArray*)[contact.postalAddresses valueForKey:#"value"];
if (addresses.count > 0) {
for (CNPostalAddress* address in addresses) {
[addrArr addObject:[formatter stringFromPostalAddress:address]];
}
}
return addrArr;
}
Just make sure that you ask the permission to read the contacts from device.
Reference link: https://gist.github.com/willthink/024f1394474e70904728
Updated:
For replacement for AddressBookUI you need to use CNContactPickerViewController. You can check the delegate methods which can be used to pickup the one or multiple contacts at a time.
This will present a inbuilt UIViewController with all the contacts and you need to implement the delegate methods of it!
To select one contact:
contactPicker:didSelectContact:
To select multiple (New Feature):
contactPicker:didSelectContacts:
CNContactPickerDelegate reference: https://developer.apple.com/library/ios/documentation/ContactsUI/Reference/CNContactPickerDelegate_Protocol/
Apple has introduced new framework for this for iOS9 and above please fine below link Link
Edit:
one more link :Link2
I'm using nst's iOS Runtime Headers to get access to the CoreTelephony.framework.
Here is his sample code:
NSBundle *b = [NSBundle bundleWithPath:#"/System/Library/PrivateFrameworks/FTServices.framework"];
BOOL success = [b load];
Class FTDeviceSupport = NSClassFromString(#"FTDeviceSupport");
id si = [FTDeviceSupport valueForKey:#"sharedInstance"];
NSLog(#"-- %#", [si valueForKey:#"deviceColor"]);
His sample usage code gives me access to FTServices.framework but when I apply the same logic, it fails since CoreTelephony does not house a class method named sharedInstance().
Should I declare and implement that myself or is there another way?
Thanks.
EDIT:
My attempt:
NSBundle *b = [NSBundle bundleWithPath:#"/System/Library/Frameworks/CoreTelephony.framework"];
BOOL success = [b load];
Class CTTelephonyNetworkInfo = NSClassFromString(#"CTTelephonyNetworkInfo");
id si = [CTTelephonyNetworkInfo valueForKey:#"sharedInstance"]; // fails here
NSLog(#"-- %#", [si valueForKey:#"cachedSignalStrength"]);
The problem is that CTTelephonyNetworkInfo actually has no property sharedInstance. Referred from here, CTTelephonyNetworkInfo is a data structure designed to house the relevant info, and can be accessed (constructed) directly through the standard [[CTTelephonyNetworkInfo alloc] init] (referred from here).
So for your case:
NSBundle *b = [NSBundle bundleWithPath:#"/System/Library/Frameworks/CoreTelephony.framework"];
BOOL success = [b load];
Class CTTelephonyNetworkInfo = NSClassFromString(#"CTTelephonyNetworkInfo");
id si = [[CTTelephonyNetworkInfo alloc] init];
NSLog(#"-- %#", [si valueForKey:#"cachedSignalStrength"]);
Make sure you test on an actual phone though! Simulators have no such information stored.
Edits:
If you want to call methods on a generated class, use performSelector: or NSInvocation class.
Background: I used same code for iOS 8.2,8.3 it was working fine.
PKPaymentAuthorizationViewController *paymentPane = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
paymentPane.delegate = self;
[self presentViewController:paymentPane animated:TRUE completion:nil];
PaymentRequest Code:
PKPaymentRequest *request = [[PKPaymentRequest alloc] init];
NSString *chargeApplePay=[NSString stringWithFormat:#"%.02f",pay];
PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:#"Grand Total"
amount:[NSDecimalNumber decimalNumberWithString:chargeApplePay]];
request.paymentSummaryItems = #[total];
request.countryCode = #"US";
request.currencyCode = #"USD";
request.supportedNetworks = #[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa];
request.merchantIdentifier = #"valid.com.myIdentifier";
request.merchantCapabilities = PKMerchantCapability3DS;
Question: Now on iOS 8.4 when I try to present my paymentPane its value is nil somehow.
Fatal Exception: NSInvalidArgumentException Application tried to
present a nil modal view controller on target .
What I have already tried by googling and using answers from stackoverflow.
Used Checks like
[PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:#[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa]]
and
[PKPaymentAuthorizationViewController canMakePayments]
Checking my merchant id is valid or not.
Checking All the code I used for request is valid or not.
Check whether you've added Credit card information in your device Passbook or not.
Check whether you can make payment using your device.
Objective C :
if ([PKPaymentAuthorizationViewController canMakePayments]) {
NSLog(#"Can Make Payments");
}
else {
NSLog(#"Can't Make payments");
}
Swift :
if PKPaymentAuthorizationViewController.canMakePayments() {
NSLog(#"Can Make Payments");
}
else {
NSLog(#"Can't Make Payments");
}
Check whether you can make payment using the allowed payment networks.
Objective C :
NSArray *paymentNetworks = [NSArray arrayWithObjects:PKPaymentNetworkMasterCard, PKPaymentNetworkVisa, PKPaymentNetworkAmex, nil];
if ([PKPaymentAuthorizationViewController canMakePaymentsUsingNetworks:paymentNetworks]) {
NSLog(#"Can Make payment with your card");
}
else {
NSLog(#"Card is not supporting");
}
Swift :
let paymentNetworks = [PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa]
if PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(paymentNetworks) {
NSLog(#"Can Make payment with your card");
}
else {
NSLog(#"Card is not supporting");
}
I have also had similar problems when running inside the Xcode debugger. As a workaround I stop the app in Xcode and then manually start the app on the iPhone or iPad.
One drawback with this is obviously that you can't debug any issues. I've had to resort to NSLog and reading the console log.
I have a commercial app that has a completely legitimate reason to see the SSID of the network it is connected to: If it is connected to a Adhoc network for a 3rd party hardware device it needs to be functioning in a different manner than if it is connected to the internet.
Everything I've seen about getting the SSID tells me I have to use Apple80211, which I understand is a private library. I also read that if I use a private library Apple will not approve the app.
Am I stuck between an Apple and a hard place, or is there something I'm missing here?
As of iOS 7 or 8, you can do this (need Entitlement for iOS 12+ as shown below):
#import SystemConfiguration.CaptiveNetwork;
/** Returns first non-empty SSID network info dictionary.
* #see CNCopyCurrentNetworkInfo */
- (NSDictionary *)fetchSSIDInfo {
NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
NSLog(#"%s: Supported interfaces: %#", __func__, interfaceNames);
NSDictionary *SSIDInfo;
for (NSString *interfaceName in interfaceNames) {
SSIDInfo = CFBridgingRelease(
CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
NSLog(#"%s: %# => %#", __func__, interfaceName, SSIDInfo);
BOOL isNotEmpty = (SSIDInfo.count > 0);
if (isNotEmpty) {
break;
}
}
return SSIDInfo;
}
Example output:
2011-03-04 15:32:00.669 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: Supported interfaces: (
en0
)
2011-03-04 15:32:00.693 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: en0 => {
BSSID = "ca:fe:ca:fe:ca:fe";
SSID = XXXX;
SSIDDATA = <01234567 01234567 01234567>;
}
Note that no ifs are supported on the simulator. Test on your device.
iOS 12
You must enable access wifi info from capabilities.
Important
To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID. Documentation link
Swift 4.2
func getConnectedWifiInfo() -> [AnyHashable: Any]? {
if let ifs = CFBridgingRetain( CNCopySupportedInterfaces()) as? [String],
let ifName = ifs.first as CFString?,
let info = CFBridgingRetain( CNCopyCurrentNetworkInfo((ifName))) as? [AnyHashable: Any] {
return info
}
return nil
}
UPDATE FOR iOS 10 and up
CNCopySupportedInterfaces is no longer deprecated in iOS 10. (API Reference)
You need to import SystemConfiguration/CaptiveNetwork.h and add SystemConfiguration.framework to your target's Linked Libraries (under build phases).
Here is a code snippet in swift (RikiRiocma's Answer):
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces) {
let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
}
}
}
return currentSSID
}
}
(Important: CNCopySupportedInterfaces returns nil on simulator.)
For Objective-c, see Esad's answer here and below
+ (NSString *)GetCurrentWifiHotSpotName {
NSString *wifiName = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info[#"SSID"]) {
wifiName = info[#"SSID"];
}
}
return wifiName;
}
UPDATE FOR iOS 9
As of iOS 9 Captive Network is deprecated*. (source)
*No longer deprecated in iOS 10, see above.
It's recommended you use NEHotspotHelper (source)
You will need to email apple at networkextension#apple.com and request entitlements. (source)
Sample Code (Not my code. See Pablo A's answer):
for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
NSString *ssid = hotspotNetwork.SSID;
NSString *bssid = hotspotNetwork.BSSID;
BOOL secure = hotspotNetwork.secure;
BOOL autoJoined = hotspotNetwork.autoJoined;
double signalStrength = hotspotNetwork.signalStrength;
}
Side note: Yup, they deprecated CNCopySupportedInterfaces in iOS 9 and reversed their position in iOS 10. I spoke with an Apple networking engineer and the reversal came after so many people filed Radars and spoke out about the issue on the Apple Developer forums.
Here's the cleaned up ARC version, based on #elsurudo's code:
- (id)fetchSSIDInfo {
NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
NSLog(#"Supported interfaces: %#", ifs);
NSDictionary *info;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
NSLog(#"%# => %#", ifnam, info);
if (info && [info count]) { break; }
}
return info;
}
This works for me on the device (not simulator). Make sure you add the systemconfiguration framework.
#import <SystemConfiguration/CaptiveNetwork.h>
+ (NSString *)currentWifiSSID {
// Does not work on the simulator.
NSString *ssid = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info[#"SSID"]) {
ssid = info[#"SSID"];
}
}
return ssid;
}
This code work well in order to get SSID.
#import <SystemConfiguration/CaptiveNetwork.h>
#implementation IODAppDelegate
#synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
CFArrayRef myArray = CNCopySupportedInterfaces();
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
NSLog(#"Connected at:%#",myDict);
NSDictionary *myDictionary = (__bridge_transfer NSDictionary*)myDict;
NSString * BSSID = [myDictionary objectForKey:#"BSSID"];
NSLog(#"bssid is %#",BSSID);
// Override point for customization after application launch.
return YES;
}
And this is the results :
Connected at:{
BSSID = 0;
SSID = "Eqra'aOrange";
SSIDDATA = <45717261 27614f72 616e6765>;
}
If you are running iOS 12 you will need to do an extra step.
I've been struggling to make this code work and finally found this on Apple's site:
"Important
To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID."
https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo
See CNCopyCurrentNetworkInfo in CaptiveNetwork: http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html.
Here's the short & sweet Swift version.
Remember to link and import the Framework:
import UIKit
import SystemConfiguration.CaptiveNetwork
Define the method:
func fetchSSIDInfo() -> CFDictionary? {
if let
ifs = CNCopySupportedInterfaces().takeUnretainedValue() as? [String],
ifName = ifs.first,
info = CNCopyCurrentNetworkInfo((ifName as CFStringRef))
{
return info.takeUnretainedValue()
}
return nil
}
Call the method when you need it:
if let
ssidInfo = fetchSSIDInfo() as? [String:AnyObject],
ssID = ssidInfo["SSID"] as? String
{
println("SSID: \(ssID)")
} else {
println("SSID not found")
}
As mentioned elsewhere, this only works on your iDevice. When not on WiFi, the method will return nil – hence the optional.
For iOS 13
As from iOS 13 your app also needs Core Location access in order to use the CNCopyCurrentNetworkInfo function unless it configured the current network or has VPN configurations:
So this is what you need (see apple documentation):
- Link the CoreLocation.framework library
- Add location-services as a UIRequiredDeviceCapabilities Key/Value in Info.plist
- Add a NSLocationWhenInUseUsageDescription Key/Value in Info.plist describing why your app requires Core Location
- Add the "Access WiFi Information" entitlement for your app
Now as an Objective-C example, first check if location access has been accepted before reading the network info using CNCopyCurrentNetworkInfo:
- (void)fetchSSIDInfo {
NSString *ssid = NSLocalizedString(#"not_found", nil);
if (#available(iOS 13.0, *)) {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSLog(#"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
} else {
CLLocationManager* cllocation = [[CLLocationManager alloc] init];
if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
[cllocation requestWhenInUseAuthorization];
usleep(500);
return [self fetchSSIDInfo];
}
}
}
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer id)CNCopyCurrentNetworkInfo(
(__bridge CFStringRef)ifnam);
NSDictionary *infoDict = (NSDictionary *)info;
for (NSString *key in infoDict.allKeys) {
if ([key isEqualToString:#"SSID"]) {
ssid = [infoDict objectForKey:key];
}
}
}
...
...
}