Re-continue these permissions in iOS development

Source: Internet
Author: User

Preface to the previous article in iOS development of these permissions, you understand it? This paper introduces some methods of obtaining and requesting the common permission, knowing that the use of these methods can basically solve the requirement of access for most applications. However, these methods are not comprehensive and do not cover all access methods. So, the author introduces some of the remaining access methods and some of the use of attention, hope to give you the development process to bring a trace of convenience. Finally, I will often use the permission request method encapsulated Open Source Library Jlauthorizationmanager to everyone, welcome to pull request and star~~permission speech recognition; Media Database/Apple Music; Siri, health data sharing, Bluetooth, residential Authority (HOMEKIT), Social account system authority, activity and physical training record, advertising identification, speech recognition Introduction header file: @import Speech; First, determine the state of the current application's permissions If the current state is notdetermined (not determined), at this time, it is necessary to call the system-provided request permission method, but also the trigger system pop-up point, this permission involves the class is Sfspeechrecognizer, the specific code is as follows:- (void) P_requestspeechrecognizeraccesswithauthorizedhandler: (void(^) ()) Authorizedhandler Unauthorizedhandler: (void(^) ()) unauthorizedhandler{sfspeechrecognizerauthorizationstatus authstatus=[Sfspeechrecognizer Authorizationstatus]; if(Authstatus = =sfspeechrecognizerauthorizationstatusnotdetermined) {         //methods for invoking system-provided access to permissions[Sfspeechrecognizer requestauthorization:^(sfspeechrecognizerauthorizationstatus status) {if(Status = =sfspeechrecognizerauthorizationstatusauthorized) {Dispatch_async (Dispatch_get_main_queue (),^{                     //after the authorization is successfulAuthorizedhandler?Authorizedhandler (): nil;            }); }Else{Dispatch_async (Dispatch_get_main_queue (),^{                    //after authorization failsUnauthorizedhandler?Unauthorizedhandler (): nil;            });            }        }]; }Else if(Authstatus = =sfspeechrecognizerauthorizationstatusauthorized) {Authorizedhandler?Authorizedhandler (): nil; }Else{Unauthorizedhandler?Unauthorizedhandler (): nil; It is important to note that the block callback that calls the Requestauthorization method is done in any sub-thread, and if you need to refresh the UI after the authorization succeeds, you need to place the corresponding method in the main thread, which I will do by default in the main thread. Follow-up permission request method is similar to this, no longer repeat. Add the specified configuration information in Info.plist as follows: Speech Recognizer Media Library/Apple Music Import header file @import MediaPlayer; Use class mpmedialibrary to access the code as follows;- (void) P_requestapplemusicaccesswithauthorizedhandler: (void(^) ()) Authorizedhandler Unauthorizedhandler: (void(^) ()) unauthorizedhandler{mpmedialibraryauthorizationstatus authstatus=[Mpmedialibrary Authorizationstatus]; if(Authstatus = =mpmedialibraryauthorizationstatusnotdetermined) {[Mpmedialibrary requestauthorization:^(mpmedialibraryauthorizationstatus status) {if(Status = =mpmedialibraryauthorizationstatusauthorized) {Dispatch_async (Dispatch_get_main_queue (),^{Authorizedhandler?Authorizedhandler (): nil;            }); }Else{Dispatch_async (Dispatch_get_main_queue (),^{Unauthorizedhandler?Unauthorizedhandler (): nil;            });    }        }]; }Else if(Authstatus = =mpmedialibraryauthorizationstatusauthorized) {Authorizedhandler?Authorizedhandler (): nil; }Else{Unauthorizedhandler?Unauthorizedhandler (): nil; Add the specified configuration information in Info.plist as follows: Mediasiri Import header file @import Intents; When different from other permissions, use Siri to capabilities the Siri switch in Xcode, Xcode automatically generates a xx.entitlements file, and when the switch is not turned on, the project runs with an error. The implementation code is as follows:- (void) P_requestsiriaccesswithauthorizedhandler: (void(^) ()) Authorizedhandler Unauthorizedhandler: (void(^) ()) unauthorizedhandler{insiriauthorizationstatus authstatus=[Inpreferences Siriauthorizationstatus]; if(Authstatus = =insiriauthorizationstatusnotdetermined) {[Inpreferences requestsiriauthorization:^(insiriauthorizationstatus status) {if(Status = =insiriauthorizationstatusauthorized) {Dispatch_async (Dispatch_get_main_queue (),^{Authorizedhandler?Authorizedhandler (): nil;            }); }Else{Dispatch_async (Dispatch_get_main_queue (),^{Unauthorizedhandler?Unauthorizedhandler (): nil;            });            }        }]; }Else if(Authstatus = =insiriauthorizationstatusauthorized) {Authorizedhandler?Authorizedhandler (): nil; }Else{Unauthorizedhandler?Unauthorizedhandler (): nil; }} Health data sharing import header file @import HealthKit; Health data sharing permissions are relatively complex relative to other permissions, and are divided into write and read-out permissions. The Info.plist in Xcode 8 requires the following two permissions to be set:    1, Privacy-Health Update Usage Description2, Privacy-Health Share Usage Description Specific implementation code:    //set the Write/share health data type-(Nsset *) Typestowrite {hkquantitytype*steptype =[Hkobjecttype Quantitytypeforidentifier:hkquantitytypeidentifierstepcount]; Hkquantitytype*distancetype =[Hkobjecttype quantitytypeforidentifier:hkquantitytypeidentifierdistancewalkingrunning]; return[Nsset Setwithobjects:steptype,distancetype, nil];}//set the permission type to read and write as follows:-(Nsset *) Typestoread {hkquantitytype*steptype =[Hkobjecttype Quantitytypeforidentifier:hkquantitytypeidentifierstepcount]; Hkquantitytype*distancetype =[Hkobjecttype quantitytypeforidentifier:hkquantitytypeidentifierdistancewalkingrunning]; return[Nsset Setwithobjects:steptype,distancetype, nil];}//need to determine device support HealthKitif([Hkhealthstore ishealthdataavailable]) {return; }hkhealthstore*healthstore =[[Hkhealthstore alloc] init]; Nsset* Typestoshare =[self typestowrite]; Nsset* Typestoread =[self typestoread]; [Healthstore requestauthorizationtosharetypes:typestoshare readtypes:typestoread Completion:^ (BOOL success, Nserror *_nullable Error) {        if(Success) {Dispatch_async (Dispatch_get_main_queue (),^{NSLog (@"Health has authorized!");        }); }Else{Dispatch_async (Dispatch_get_main_queue (),^{NSLog (@"Health has not authorized!");        }); }]; Bluetooth needs to import header file @import corebluetooth; The Bluetooth permission detection is more complicated than other, need to detect the Bluetooth status in the agent; Get Bluetooth permissions:- (void) checkbluetoothaccess {Cbcentralmanager*cbmanager =[[Cbcentralmanager alloc] initwithdelegate:self Queue:nil]; Cbmanagerstate State=[Cbmanager State]; if(state = =Cbmanagerstateunknown) {NSLog (@"unknown!"); }    Else if(state = =cbmanagerstateunauthorized) {NSLog (@"unauthorized!"); }    Else{NSLog (@"granted!"); }}- (void) Centralmanagerdidupdatestate: (Cbcentralmanager *) Central {//This proxy method will be called when the Bluetooth permission state changes, and can modify the UI or data access according to different state. Request Bluetooth Permission- (void) requestbluetoothaccess {Cbcentralmanager*cbmanager =[[Cbcentralmanager alloc] initwithdelegate:self Queue:nil];//This method displays the user-approved popup window[Cbmanager Scanforperipheralswithservices:nil options:nil];} The Housing Authority (HOMEKIT) needs to import the header file @import HomeKit; Here's how to request permissions HomeKit:- (void) requesthomeaccess {Self.homemanager=[[Hmhomemanager alloc] init];//when the proxy method is set, user permissions are requestedSelf.homemanager.Delegate=Self ;}- (void) Homemanagerdidupdatehomes: (Hmhomemanager *) Manager {if(Manager.homes.count >0) {        //the number of home is not empty, which means that user rights have passed    }    Else{__weak Hmhomemanager*weakhomemanager = Manager;//Prevent Memory Leak[Manager Addhomewithname:@"Test Home"completionhandler:^ (Hmhome *home, Nserror *error) {                        if(!error) {               //permissions Allow            }            Else {                if(Error.code = =hmerrorcodehomeaccessnotauthorized) {                   //permissions are not allowed                }                Else {                    //processing the error generated by the request                }            }                        if(Home) {[Weakhomemanager removehome:home Completionhandler:^ (Nserror *_nullable Error) {                    //Removing Home                }];    }        }]; }} Social account system permissions Import header file @import Accounts; get the corresponding permissions:- (void) Checksocialaccountauthorizationstatus: (NSString *) Accounttypeindentifier {acaccountstore*accountstore =[[Acaccountstore alloc] init]; Acaccounttype*socialaccount =[Accountstore Accounttypewithaccounttypeidentifier:accounttypeindentifier]; if([Socialaccount accessgranted]) {NSLog (@"permission passed."); }Else{NSLog (@"Permission not passed! "); }}accounttypeindentifier can be of the following types:Accounts_extern NSString*Constacaccounttypeidentifiertwitter ns_available (NA, 5_0); Accounts_extern NSString*ConstAcaccounttypeidentifierfacebook ns_available (NA, 6_0); Accounts_extern NSString*ConstAcaccounttypeidentifiersinaweibo ns_available (NA, 6_0); Accounts_extern NSString*ConstAcaccounttypeidentifiertencentweibo ns_available (NA, 7_0); Accounts_extern NSString*ConstAcaccounttypeidentifierlinkedin ns_available (Na, NA); request the corresponding permission:- (void) requesttwitteraccess {acaccountstore*accountstore =[[Acaccountstore alloc] init]; Acaccounttype*accounttype =[Accountstore Accounttypewithaccounttypeidentifier:accounttypeidentifier]; [Accountstore requestaccesstoaccountswithtype:accounttype Options:nil Completion:^ (BOOL Granted, Nserror *error) {Dispatch_async (Dispatch_get_main_queue (),^{           if(granted) {NSLog (@"authorization passed."); }Else{NSLog (@"Authorization not approved");    }        }); }];} Activity and physical Training record import header file @import coremotion; Specific implementation code:    //access to activity and fitness training recordsCmmotionactivitymanager *cmmanager =[[Cmmotionactivitymanager alloc] init]; Nsoperationqueue*queue =[[Nsoperationqueue alloc] init]; [Cmmanager startactivityupdatestoqueue:queue Withhandler:^ (Cmmotionactivity *activity) {                //After the authorization succeeds, it will enter the block method, and the authorization failure will not enter the block method.}]; Advertising identity Import header file @import adsupport; Gets the permission status of the ad identity:BOOL Isauthorizedforad=[[Asidentifiermanager Sharedmanager] isadvertisingtrackingenabled]; Before using the Advertisingidentifier attribute, The above method must be called to determine whether support, if the above method return value is no, then advertising ID access will be limited. Summary of the above two articles, the handling of the iOS system permissions problem basically covered completely; not all access to the permissions are explicitly called methods, and some are accessed during use, such as location permissions, bluetooth sharing permissions, HomeKit permissions, activity and fitness training rights, These permissions are used to pay attention to the permission handling in the callback method; HomeKit, HealthKit, Siri need to turn on the switch in capabilities, The projectname.entitlements file is generated, and the open Source Library Jlauthorizationmanager supports the integration of most common access to access, convenient use of welcome to pull request or star;

Re-continue these permissions in iOS development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.