Detecting hardware and sensors in iOS

Source: Internet
Author: User

The first thing to know is that you need to see if the hardware or sensor you need is there, not what the device is capable of. For example, you cannot assume that only the iphone has a microphone, and you should use the API to see if the microphone exists. The first advantage of this code is that it is automatically compatible with new devices and external microphones that will be available in the future.

A second advantage? This piece of code has only one line.

The correct way to check microphone availability

1234
-(BOOL) microphoneavailable  {avaudiosession *session = [Avaudiosession Sharedinstance];return session.inputisavailable;}

For microphones, you will also need to detect changes in input device alerts. That is, when a user inserts a microphone, the viewDidAppear Record button on the UI is activated, in addition to making the appropriate modifications in. Sounds pretty cool, doesn't it? The following is the specific implementation method.

Check if the microphone is plugged in

1 2 3 4 5 6 7 8 9101112
void Audioinputpropertylistener (void* inclientdata,audiosessionpropertyid InID, UInt32 indatasize, const void *inData)  {    UInt32 isavailable = * (uint32*) inData;        BOOL micavailable = (isavailable > 0);    Add code for Update UI}-(void) viewdidload  {    [super viewdidload];    Audiosessionaddpropertylistener (Kaudiosessionproperty_audioinputavailable,audioinputpropertylistener, nil);}

Here, all you have to do is kAudioSessionProperty_AudioInputAvailable add a property listener and check its value in the callback.

As long as you add a few lines of code, you can write the correct device detection code. Next, you need to extend this code to support other hardware and sensors.

AudioSessionPropertyListenersthe use NSNotification is much like the observed event. When you add a property listener to a class, you need to be responsible for removing it at the appropriate time. In the previous example, because the viewDidLoad property listener was added in, it needs to be didReceiveMemoryWarning removed from the method.

1. Detecting Camera Type

The iphone initially had only one webcam and later added a front-facing camera to iphone 4. IPod Touch does not have a webcam until the fourth generation. The iphone 4 has a front-facing camera, an ipad 1 (bigger than the iphone 4) without a webcam, while the later ipad 2 has a front-and rear-facing camera. All this means that you should not write code without assuming the functionality of the device. It's actually more convenient to use the API.

UIImagePickerControllerclass contains class methods that detect the availability of source types.

Detect if a camera is present

1234
-(BOOL) cameraavailable  {  return [Uiimagepickercontroller issourcetypeavailable: Uiimagepickercontrollersourcetypecamera];}

Detect the presence of a front-facing camera

123456789
-(BOOL) frontcameraavailable{#ifdef __iphone_4_0  return [Uiimagepickercontroller iscameradeviceavailable: Uiimagepickercontrollercameradevicefront]; #else  return NO; #endif}

Detects the front-facing camera and needs to be running in iOS 4 or later. Enumeration types are UIImagePickerControllerCameraDeviceFront available only in iOS 4 and later, because all devices with front-facing cameras (iPhone 4 and ipad 2) Use iOS 4 and later. So you use a macro that returns if the device is using iOS 3 or earlier NO .

Similarly, you can check whether the camera on your device has video recording capabilities. The IPhone 3GS and the updated device's camera support recording video. You can use the following code to check.

Detects if the camera supports video recording

1 2 3 4 5 6 7 8 910111213
-(BOOL) videocameraavailable  {  uiimagepickercontroller *picker =[[uiimagepickercontroller alloc] init];// First call the previous method to check if there is a camera if (![ Self cameraavailable])  return NO; Nsarray *sourcetypes = [Uiimagepickercontroller availablemediatypesforsourcetype: Uiimagepickercontrollersourcetypecamera];  if (![ Sourcetypes containsobject: (NSString *) Kuttypemovie]) {    return NO;  }  return YES;}

This code enumerates the available media types for a given camera and then determines if it contains kUTTypeMovie .

2. Check if photo gallery is empty

If you're using a webcam, you'll almost always use a photo gallery. Before calling UIImagePicker Show user albums, you need to make sure that there are photos in it. You can check if the album is empty by checking the presence of the camera, as long as UIImagePickerControllerSourceTypePhotoLibrary UIImagePickerControllerSourceTypeSavedPhotosAlbum it is passed or as a source type.

3. Detect if the camera flash is present

So far, the only device with a camera flash is the iphone 4^(1)^. In the coming years, there will be more and more devices with camera flash. Use UIImagePickerController the class method to check whether the camera flash is present easily.

The iphone 4S and iphone 5 were both released when ^(1)^ translated the book, and they also come with a camera flash. --Translator's note

Detects if the camera flash is present

12345678
-(BOOL) cameraflashavailable  {#ifdef __iphone_4_0  return [Uiimagepickercontroller Isflashavailableforcameradevice:uiimagepickercontrollercameradevicerear]; #else  return NO; #endif}
4. Detect if the gyroscope is present

The gyroscope is an interesting new sensor on the iphone 4. Devices released after the iphone 4, including the new ipad and iphone 5, all have gyroscopes. A gyroscope is used to measure the relative changes in the physical location of a device. In contrast, the accelerometer can only measure the force's size, not the twist. With gyroscopes, game developers may even achieve six-axis control, similar to the features offered by the Sony PlayStation 3 controller or Nintendo's Wii controller. You can use CoreMotion.framework the provided API to detect if a gyroscope exists.

Detects if a gyroscope exists

123456789
-(BOOL) gyroscopeavailable  {#ifdef __iphone_4_0  cmmotionmanager *motionmanager = [[Cmmotionmanager alloc] INIT];  BOOL gyroavailable = motionmanager.gyroavailable;  return gyroavailable; #else  return NO; #endif}

If the gyroscope is an important feature in your application, and your target device does not have a gyroscope, you must design the application with a different input method. Or you can specify them in the keys in the app's info.plist UIRequiredDeviceCapablities to prevent devices without gyroscopes from installing the app. This key is further described later in this chapter.

5. Test Compass or magnetometer

Compass usability can be checked using CoreLocation.framework the CLLocationManager classes in. Call CLLocationManager the headingAvailable method in, and if the return value is true, you can use the compass in your app. The compass is of great use in location-related applications and in applications where augmented reality technology is used.

6. Detect Retina Screen

As an iOS developer, you already know that the retina screen (Retina display) needs to be met by adding a @2x image file to each resource used in the app. But if you want to download pictures from a remote server, a device with a retina screen needs to download a picture resolution of twice times the resolution of a normal screen image.

The photo browser app is a good example of a Flickr viewer or Instagram. When the user launches the app on iphone 4, new ipad, or iphone 5, the downloaded image resolution should be twice times the resolution of the non-Retina screen device slice. Some developers choose to ignore it and download high-resolution images directly for all devices, but this is a bit of a waste of bandwidth and may be much slower to download even through the edge. Instead, you should determine that the device is using a Retina screen and then download the high-resolution image. This check is easy.

Check if the device is using a Retina screen

12345678
-(BOOL) retinadisplaycapable  {int scale = 1.0; UIScreen *screen = [UIScreen mainscreen];if ([Screen respondstoselector: @selector (scale)]) scale  = Screen.scale;if (Scale = = 2.0f) return yes;else return NO;

In this code, you'll find the device and check to see mainScreen if the device can display a high-resolution picture for the retina screen. This way, if Apple launches an external Retina screen (possibly an updated Apple Cinema Display) that supports the current generation of ipad output directly in the retina mode, then your app will still work without any modifications.

7. Detect Vibration Alert function

When writing a book, only the various versions of the iphone have a vibrating alert feature. Unfortunately, there is no public API to detect whether the device supports vibration. However, AudioToolbox.framework there are two ways to selectively vibrate different versions of the iphone:

12
Audioservicesplayalertsound (ksystemsoundid_vibrate); Audioservicesplaysystemsound (ksystemsoundid_vibrate);

The first method vibrates the iphone, while on the ipod touch/ipad a "beep" sound is emitted. The second method only vibrates the iphone. It does nothing on a device that does not support vibration. If you're developing a game that warns of danger through vibrating devices, or develops a maze game that vibrates when a player hits a wall, the second method should be used. The first method is used to alert the user, including vibrations and beeps, while the second method can only be used to emit vibrations.

8. Detect REMOTE Control function

iOS apps can handle remote control events that are triggered by pressing a button on an external headset. To handle such events, receive notifications using the following methods:

1
[[UIApplication sharedapplication] beginreceivingremotecontrolevents];

The firstResponder following methods are implemented in:

1
Remotecontrolreceivedwithevent:

Call the following method to ensure that the feature is turned off when these events are not needed:

1
[[UIApplication sharedapplication] endreceivingremotecontrolevents];
9. Detect Phone Call function

You can check whether the device supports making calls by checking to see if it can open tel: the type's URL. UIApplicationclass canOpenURL: makes it easy to check whether there is an app on the device that can handle a particular type of URL. On the iphone, such tel: URLs are handled by the phone app on the iphone. This method can also be used to check whether a specific app that handles a given URL has been installed on the device.

Detect phone Call function

1234
-(BOOL) canmakephonecalls  {  return [[UIApplication Sharedapplication]canopenurl:[nsurl urlwithstring:@] Tel ://"]];}

Usability tips on ipod Touch, developers should completely hide the phone-facing features. For example, if you develop a yellow pages application that displays a list of phone numbers on the internet, you should only show the button on the device that makes the phone call. Do not simply disable it (because the user cannot enable it for anything) or display an error alert. As a precedent, displaying a "not IPhone" error alert on ipod Touch will prevent the app from being reviewed by Apple's app review department.

Detecting hardware and sensors in iOS

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.