AVAudioSession

Struct AVAudioSession 

Source
pub struct AVAudioSession { /* private fields */ }
Available on crate feature AVAudioSession only.
Expand description

Implementations§

Source§

impl AVAudioSession

Source

pub unsafe fn sharedInstance() -> Retained<AVAudioSession>

Return singleton instance.

Source

pub unsafe fn availableCategories( &self, ) -> Retained<NSArray<AVAudioSessionCategory>>

Available on crate feature AVAudioSessionTypes only.

Get the list of categories available on the device. Certain categories may be unavailable on particular devices. For example, AVAudioSessionCategoryRecord will not be available on devices that have no support for audio input.

This property is not atomic.

§Safety

This might not be thread-safe.

Source

pub unsafe fn setCategory_error( &self, category: &AVAudioSessionCategory, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set session category.

Source

pub unsafe fn setCategory_withOptions_error( &self, category: &AVAudioSessionCategory, options: AVAudioSessionCategoryOptions, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set session category with options.

Source

pub unsafe fn setCategory_mode_options_error( &self, category: &AVAudioSessionCategory, mode: &AVAudioSessionMode, options: AVAudioSessionCategoryOptions, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set session category and mode with options.

Source

pub unsafe fn setCategory_mode_routeSharingPolicy_options_error( &self, category: &AVAudioSessionCategory, mode: &AVAudioSessionMode, policy: AVAudioSessionRouteSharingPolicy, options: AVAudioSessionCategoryOptions, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set session category, mode, routing sharing policy, and options.

Use of the long-form route sharing policy is only valid in conjunction with a limited set of category, mode, and option values.

Allowed categories: AVAudioSessionCategoryPlayback.

Allowed modes: AVAudioSessionModeDefault, AVAudioSessionModeMoviePlayback, AVAudioSessionModeSpokenAudio.

Allowed options: None. Options are allowed when changing the routing policy back to Default, however.

Source

pub unsafe fn category(&self) -> Retained<AVAudioSessionCategory>

Available on crate feature AVAudioSessionTypes only.

Get session category. Examples: AVAudioSessionCategoryRecord, AVAudioSessionCategoryPlayAndRecord, etc.

Source

pub unsafe fn categoryOptions(&self) -> AVAudioSessionCategoryOptions

Available on crate feature AVAudioSessionTypes only.

Get the current set of AVAudioSessionCategoryOptions.

Source

pub unsafe fn routeSharingPolicy(&self) -> AVAudioSessionRouteSharingPolicy

Available on crate feature AVAudioSessionTypes only.

Get the route sharing policy.

See AVAudioSessionRouteSharingPolicy for a description of the available policies. See setCategory:mode:routeSharingPolicy:options:error: for additional discussion.

Source

pub unsafe fn availableModes(&self) -> Retained<NSArray<AVAudioSessionMode>>

Available on crate feature AVAudioSessionTypes only.

Get the list of modes available on the device. Certain modes may be unavailable on particular devices. For example, AVAudioSessionModeVideoRecording will not be available on devices that have no support for recording video.

Source

pub unsafe fn setMode_error( &self, mode: &AVAudioSessionMode, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set the session’s mode.

Modes modify the audio category in order to introduce behavior that is tailored to the specific use of audio within an application. Examples: AVAudioSessionModeVideoRecording, AVAudioSessionModeVoiceChat, AVAudioSessionModeMeasurement, etc.

Source

pub unsafe fn mode(&self) -> Retained<AVAudioSessionMode>

Available on crate feature AVAudioSessionTypes only.

Get the session’s mode.

Source

pub unsafe fn setAllowHapticsAndSystemSoundsDuringRecording_error( &self, in_value: bool, ) -> Result<(), Retained<NSError>>

Set allowHapticsAndSystemSoundsDuringRecording to YES in order to allow system sounds and haptics to play while the session is actively using audio input. Default value is NO.

Source

pub unsafe fn allowHapticsAndSystemSoundsDuringRecording(&self) -> bool

Whether system sounds and haptics can play while the session is actively using audio input.

Source

pub unsafe fn recordPermission(&self) -> AVAudioSessionRecordPermission

👎Deprecated: Please use AVAudioApplication recordPermission
Available on crate feature AVAudioSessionTypes only.

Returns an enum indicating whether the user has granted or denied permission to record, or has not been asked

Source

pub unsafe fn requestRecordPermission(&self, response: &DynBlock<dyn Fn(Bool)>)

👎Deprecated: Please use AVAudioApplication requestRecordPermissionWithCompletionHandler
Available on crate feature block2 only.

Checks to see if calling process has permission to record audio.

The ‘response’ block will be called immediately if permission has already been granted or denied. Otherwise, it presents a dialog to notify the user and allow them to choose, and calls the block once the UI has been dismissed. ‘granted’ indicates whether permission has been granted. Note that the block may be called in a different thread context.

Source

pub unsafe fn overrideOutputAudioPort_error( &self, port_override: AVAudioSessionPortOverride, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Use this method to temporarily override the output to built-in speaker.

This method is only valid for a session using PlayAndRecord category. This change remains in effect only until the current route changes or you call this method again with the AVAudioSessionPortOverrideNone option. Sessions using PlayAndRecord category that always want to prefer the built-in speaker output over the receiver, should use AVAudioSessionCategoryOptionDefaultToSpeaker instead.

Source

pub unsafe fn setPreferredInput_error( &self, in_port: Option<&AVAudioSessionPortDescription>, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionRoute only.

Select a preferred input port for audio routing.

If the input port is already part of the current audio route, this will have no effect. Otherwise, selecting an input port for routing will initiate a route change to use the preferred input port. Setting a nil value will clear the preference.

Source

pub unsafe fn preferredInput( &self, ) -> Option<Retained<AVAudioSessionPortDescription>>

Available on crate feature AVAudioSessionRoute only.

Get the preferred input port. Will be nil if no preference has been set.

Source

pub unsafe fn setPrefersNoInterruptionsFromSystemAlerts_error( &self, in_value: bool, ) -> Result<(), Retained<NSError>>

Set ringtone and alert interruption preference.

Inform the system when the session prefers to not be interrupted by ringtones and alerts. By setting this property to YES, clients will not be interrupted by incoming call notifications and other alerts. Starting in iOS 14.0, users can set a global preference for incoming call display style to “Banner” or “Full Screen”. With “Banner” display style, if below property is set to YES then system audio will be silenced. Thus, clients will not be interrupted on incoming call notification and user will have opportunity to accept or decline the call. If call is declined, the session will not be interrupted, but if user accepts the incoming call, the session will be interrupted. With display style set as “Full Screen”, below property will have no effect and clients will be interrupted by incoming calls. Apps that record audio and/or video and apps that are used for music performance are candidates for using this feature.

Source

pub unsafe fn prefersNoInterruptionsFromSystemAlerts(&self) -> bool

This property is not atomic.

§Safety

This might not be thread-safe.

Source

pub unsafe fn renderingMode(&self) -> AVAudioSessionRenderingMode

Available on crate feature AVAudioSessionTypes only.

Get the currently resolved rendering mode to badge content appropriately. Clients should use this property to determine what to badge content as.

Source

pub unsafe fn setPrefersEchoCancelledInput_error( &self, value: bool, ) -> Result<(), Retained<NSError>>

Set a preference to enable echo cancelled input on supported hardware

Applications might want to record the built-in microphone’s input while also playing audio out via the built-in speaker. Enabling echo cancelled input is useful when the application needs the input signal to be clear of any echoes from the audio playing out of the built-in speaker.

Audio sessions using Voice Processor don’t need this option as echo cancellation is implicitly applied for those routes. The Voice Processor solution is tuned for voice signals, unlike this option, which is tuned for better capture of wider range of audio signals in the presence of built-in speaker echo.

This option is valid only when used with AVAudioSessionCategoryPlayAndRecord and AVAudioSessionModeDefault and is only available on certain 2024 or later iPhone models. Support can be queried using property isEchoCancelledInputAvailable. Other recording sessions might be interrupted if this option is not compatible with sessions that are already recording.

After an audio session goes active, isEchoCancelledInputEnabled property can be queried to check if the option was honored. Note that the enabled state may change after route changes, e.g. if user plugs in a headset, that route might not support echo cancellation.

Source

pub unsafe fn prefersEchoCancelledInput(&self) -> bool

This property is not atomic.

§Safety

This might not be thread-safe.

Source

pub unsafe fn isEchoCancelledInputEnabled(&self) -> bool

Returns YES if echo cancelled input is successfully enabled on an active session. Please see prefersEchoCancelledInput above for more details.

This property is not atomic.

§Safety

This might not be thread-safe.

Source

pub unsafe fn isEchoCancelledInputAvailable(&self) -> bool

Query whether built-in mic / built-in speaker route supports echo cancellation for the session’s given category and mode. Returns YES if device model supports echo cancellation and the audio category is PlayAndRecord and the mode is Default.

This property is not atomic.

§Safety

This might not be thread-safe.

Source

pub unsafe fn setOutputMuted_error( &self, muted: bool, ) -> Result<(), Retained<NSError>>

Sets a Boolean value to inform the system to mute the session’s output audio. The default value is false (unmuted).

This property is supported with all categories and modes, except for AVAudioSessionCategoryPlayAndRecord where it is only supported with AVAudioSessionModeDefault. Changing the mode to non-default mode with AVAudioSessionCategoryPlayAndRecord category will cause the session to unmute.

Changes in output mute state can be observed via AVAudioSessionOutputMuteStateChangeNotification. If this value is set to true, AVAudioSessionUserIntentToUnmuteOutputNotification may be sent when a user hints to unmute by changing the volume.

  • Note: This will not mute system sounds and haptics.

  • Parameters:

  • muted: A Boolean value to set the audio output to the desired muted state.

  • error: A pointer to an error object. If an error occurs, the framework sets the pointer to an error object that describes the failure.

Source

pub unsafe fn isOutputMuted(&self) -> bool

A Boolean value that indicates whether audio output is in a muted state.

Source§

impl AVAudioSession

Activation.

Source

pub unsafe fn setActive_error( &self, active: bool, ) -> Result<(), Retained<NSError>>

Set the session active or inactive.

Note that activating an audio session is a synchronous (blocking) operation. Therefore, we recommend that applications not activate their session from a thread where a long blocking operation will be problematic. Apps may activate a AVAudioSessionCategoryPlayback session when another app is hosting a call (to start a SharePlay activity for example). However, they are not permitted to capture the microphone of the active call, so attempts to activate a session with category AVAudioSessionCategoryRecord or AVAudioSessionCategoryPlayAndRecord will fail with error AVAudioSessionErrorCodeInsufficientPriority. When deactivating a session, the caller is required to first stop or pause all running I/Os (e.g. audio queues, players, recorders, converters, remote I/Os, etc.). Starting in iOS 8, if the session has running I/Os at the time that deactivation is requested, the session will be deactivated, but the method will return NO and populate the NSError with the code property set to AVAudioSessionErrorCodeIsBusy to indicate the misuse of the API. Prior to iOS 8, the session would have remained active if it had running I/Os at the time of the deactivation request. Starting in iOS 19.0, deactivating while IO is running will no longer return AVAudioSessionErrorCodeIsBusy.

Source

pub unsafe fn setActive_withOptions_error( &self, active: bool, options: AVAudioSessionSetActiveOptions, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.
Source

pub unsafe fn activateWithOptions_completionHandler( &self, options: AVAudioSessionActivationOptions, handler: &DynBlock<dyn Fn(Bool, *mut NSError)>, )

Available on crate features AVAudioSessionTypes and block2 only.

Asynchronously activate the session.

This is a relatively time consuming operation. The completion handler will be called when the activation completes or if an error occurs while attempting to activate the session. If the session is configured to use AVAudioSessionRouteSharingPolicyLongFormAudio on watchOS, this method will also cause a route picker to be presented to the user in cases where an appropriate output route has not already been selected automatically. watchOS apps using AVAudioSessionRouteSharingPolicyLongFormAudio should be prepared for this method to fail if no eligible audio route can be activated or if the user cancels the route picker view.

Source§

impl AVAudioSession

AVAudioSessionHardwareConfiguration.

this category deals with the set of properties that reflect the current state of audio hardware in the current route. Applications whose functionality depends on these properties should reevaluate them any time the route changes.

Source

pub unsafe fn setPreferredSampleRate_error( &self, sample_rate: c_double, ) -> Result<(), Retained<NSError>>

The preferred hardware sample rate for the session. The actual sample rate may be different.

Source

pub unsafe fn preferredSampleRate(&self) -> c_double

Source

pub unsafe fn setPreferredIOBufferDuration_error( &self, duration: NSTimeInterval, ) -> Result<(), Retained<NSError>>

The preferred hardware IO buffer duration in seconds. The actual IO buffer duration may be different.

Source

pub unsafe fn preferredIOBufferDuration(&self) -> NSTimeInterval

Source

pub unsafe fn setPreferredInputNumberOfChannels_error( &self, count: NSInteger, ) -> Result<(), Retained<NSError>>

Sets the number of input channels that the app would prefer for the current route

Source

pub unsafe fn preferredInputNumberOfChannels(&self) -> NSInteger

Source

pub unsafe fn setPreferredOutputNumberOfChannels_error( &self, count: NSInteger, ) -> Result<(), Retained<NSError>>

Sets the number of output channels that the app would prefer for the current route

Source

pub unsafe fn preferredOutputNumberOfChannels(&self) -> NSInteger

Source

pub unsafe fn setPreferredInputOrientation_error( &self, orientation: AVAudioStereoOrientation, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Sets the preferred input orientation. The input orientation determines which directions will be left and right when a built-in mic data source with the AVAudioSessionPolarPatternStereo polar pattern is selected. Typically, this orientation should match how the user is holding the device while recording, which will match the application’s interface orientation when a single app is on the screen. The actual input orientation may be different, for example, if another app’s session is in control of routing. The input orientation is independent of the orientation property of an AVAudioSessionDataSourceDescription.

Source

pub unsafe fn preferredInputOrientation(&self) -> AVAudioStereoOrientation

Available on crate feature AVAudioSessionTypes only.
Source

pub unsafe fn inputOrientation(&self) -> AVAudioStereoOrientation

Available on crate feature AVAudioSessionTypes only.

Describes the orientation of the input data source (valid for the built-in mic input data source when a stereo polar pattern is selected).

Source

pub unsafe fn maximumInputNumberOfChannels(&self) -> NSInteger

Returns the largest number of audio input channels available for the current route

Source

pub unsafe fn maximumOutputNumberOfChannels(&self) -> NSInteger

Returns the largest number of audio output channels available for the current route

Source

pub unsafe fn setInputGain_error( &self, gain: c_float, ) -> Result<(), Retained<NSError>>

A value defined over the range [0.0, 1.0], with 0.0 corresponding to the lowest analog gain setting and 1.0 corresponding to the highest analog gain setting.

Attempting to set values outside of the defined range will result in the value being “clamped” to a valid input. This is a global input gain setting that applies to the current input source for the entire system. When no applications are using the input gain control, the system will restore the default input gain setting for the input source. Note that some audio accessories, such as USB devices, may not have a default value. This property is only valid if inputGainSettable is true. Note: inputGain is key-value observable.

Source

pub unsafe fn inputGain(&self) -> c_float

value in range [0.0, 1.0]

Source

pub unsafe fn isInputGainSettable(&self) -> bool

True when audio input gain is available. Some input ports may not provide the ability to set the input gain, so check this value before attempting to set input gain.

Source

pub unsafe fn isInputAvailable(&self) -> bool

True if input hardware is available. Key-value observable.

Source

pub unsafe fn inputDataSources( &self, ) -> Option<Retained<NSArray<AVAudioSessionDataSourceDescription>>>

Available on crate feature AVAudioSessionRoute only.

DataSource methods are for use with routes that support input or output data source selection.

If the attached accessory supports data source selection, the data source properties/methods provide for discovery and selection of input and/or output data sources. Note that the properties and methods for data source selection below are equivalent to the properties and methods on AVAudioSessionPortDescription. The methods below only apply to the currently routed ports.

Key-value observable.

Source

pub unsafe fn inputDataSource( &self, ) -> Option<Retained<AVAudioSessionDataSourceDescription>>

Available on crate feature AVAudioSessionRoute only.

Obtain the currently selected input data source. Will be nil if no data sources are available.

Source

pub unsafe fn setInputDataSource_error( &self, data_source: Option<&AVAudioSessionDataSourceDescription>, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionRoute only.

Select a new input data source. Setting a nil value will clear the data source preference.

Source

pub unsafe fn outputDataSources( &self, ) -> Option<Retained<NSArray<AVAudioSessionDataSourceDescription>>>

Available on crate feature AVAudioSessionRoute only.

See inputDataSources for background. Key-value observable.

Source

pub unsafe fn outputDataSource( &self, ) -> Option<Retained<AVAudioSessionDataSourceDescription>>

Available on crate feature AVAudioSessionRoute only.

Obtain the currently selected output data source. Will be nil if no data sources are available.

Source

pub unsafe fn setOutputDataSource_error( &self, data_source: Option<&AVAudioSessionDataSourceDescription>, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionRoute only.

Select a new output data source. Setting a nil value will clear the data source preference.

Source

pub unsafe fn sampleRate(&self) -> c_double

The current hardware sample rate. Is key-value observable (starting iOS 18.0).

Source

pub unsafe fn inputNumberOfChannels(&self) -> NSInteger

The current number of hardware input channels. Is key-value observable.

Source

pub unsafe fn outputNumberOfChannels(&self) -> NSInteger

The current number of hardware output channels. Is key-value observable.

Source

pub unsafe fn inputLatency(&self) -> NSTimeInterval

The current hardware input latency in seconds.

Source

pub unsafe fn outputLatency(&self) -> NSTimeInterval

The current hardware output latency in seconds.

Source

pub unsafe fn IOBufferDuration(&self) -> NSTimeInterval

The current hardware IO buffer duration in seconds. Is key-value observable.

Source

pub unsafe fn supportedOutputChannelLayouts( &self, ) -> Retained<NSArray<AVAudioChannelLayout>>

Available on crate feature AVAudioChannelLayout only.

Get an array of channel layouts that the current route supports. This property is only supported when the output is routed to ports of type AVAudioSessionPortCarAudio or AVAudioSessionPortAirPlay Otherwise, an empty array will be returned. Note that this will return an empty array if session is inactive. Clients should listen to AVAudioSessionRenderingCapabilitiesChangeNotification to be notified when this changes.

Source§

impl AVAudioSession

Observation.

Source

pub unsafe fn isOtherAudioPlaying(&self) -> bool

True when another application is playing audio.

Note: As of iOS 8.0, Apple recommends that most applications use secondaryAudioShouldBeSilencedHint instead of this property. The otherAudioPlaying property will be true if any other audio (including audio from an app using AVAudioSessionCategoryAmbient) is playing, whereas the secondaryAudioShouldBeSilencedHint property is more restrictive in its consideration of whether primary audio from another application is playing.

Source

pub unsafe fn secondaryAudioShouldBeSilencedHint(&self) -> bool

True when another application with a non-mixable audio session is playing audio.

Applications may use this property as a hint to silence audio that is secondary to the functionality of the application. For example, a game app using AVAudioSessionCategoryAmbient may use this property to decide to mute its soundtrack while leaving its sound effects unmuted. Note: This property is closely related to AVAudioSessionSilenceSecondaryAudioHintNotification.

Source

pub unsafe fn outputVolume(&self) -> c_float

The current output volume. Value in range [0.0, 1.0]. Is key-value observable.

Source

pub unsafe fn promptStyle(&self) -> AVAudioSessionPromptStyle

Available on crate feature AVAudioSessionTypes only.

The prompt style is a hint to sessions using AVAudioSessionModeVoicePrompt to alter the type of prompts they issue in response to other audio activity on the system, such as Siri and phone calls. This property is key-value observable.

Source§

impl AVAudioSession

RoutingConfiguration.

Source

pub unsafe fn availableInputs( &self, ) -> Option<Retained<NSArray<AVAudioSessionPortDescription>>>

Available on crate feature AVAudioSessionRoute only.

Get the set of input ports that are available for routing.

Note that this property only applies to the session’s current category and mode. For example, if the session’s current category is AVAudioSessionCategoryPlayback, there will be no available inputs.

On iOS, clients can listen to AVAudioSessionAvailableInputsChangeNotification to be notified when this changes.

Source

pub unsafe fn currentRoute(&self) -> Retained<AVAudioSessionRouteDescription>

Available on crate feature AVAudioSessionRoute only.

A description of the current route, consisting of zero or more input ports and zero or more output ports

Source

pub unsafe fn setAggregatedIOPreference_error( &self, in_io_type: AVAudioSessionIOType, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Controls whether audio input and output are aggregated. Only valid in combination with AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryMultiRoute.

See the AVAudioSessionIOType documentation for a more detailed explanation of why a client may want to change the IO type.

Source

pub unsafe fn setSupportsMultichannelContent_error( &self, in_value: bool, ) -> Result<(), Retained<NSError>>

Set YES to inform the system if the app can supply multichannel audio content. Default value is NO. This property is intended to be used by ‘Now Playing’ applications. See https://developer.apple.com/documentation/mediaplayer/becoming_a_now_playable_app for more information about what it means to be a ‘Now Playing’ application. Typically ‘Now Playing’ applications will also use AVAudioSessionRouteSharingPolicyLongFormAudio or AVAudioSessionRouteSharingPolicyLongFormVideo.

Source

pub unsafe fn supportsMultichannelContent(&self) -> bool

Source

pub unsafe fn setPrefersInterruptionOnRouteDisconnect_error( &self, in_value: bool, ) -> Result<(), Retained<NSError>>

Use this method to opt in or opt out of interruption on route disconnect policy.

As described in the Audio Session Programming Guide, most media playback apps are expected to pause playback if the route change reason is AVAudioSessionRouteChangeReasonOldDeviceUnavailable.

Starting in iOS 17, by default Now Playing sessions will be interrupted if they are active when a route change occurs because of a disconnect event. All other sessions will not be interrupted due to a disconnect event.

Source

pub unsafe fn prefersInterruptionOnRouteDisconnect(&self) -> bool

Indicates if session will be interrupted on route disconnect.

Source§

impl AVAudioSession

MicrophoneInjection.

Source

pub unsafe fn setPreferredMicrophoneInjectionMode_error( &self, in_value: AVAudioSessionMicrophoneInjectionMode, ) -> Result<(), Retained<NSError>>

Available on crate feature AVAudioSessionTypes only.

Set the preferred form of audio injection into another app’s input stream See AVAudioSessionMicrophoneInjectionMode for available modes

Source

pub unsafe fn preferredMicrophoneInjectionMode( &self, ) -> AVAudioSessionMicrophoneInjectionMode

Available on crate feature AVAudioSessionTypes only.
Source

pub unsafe fn isMicrophoneInjectionAvailable(&self) -> bool

Indicates if microphone injection is available. Observe AVAudioSessionMicrophoneInjectionCapabilitiesChangeNotification for changes to this property

Source§

impl AVAudioSession

AVAudioSessionDeprecated.

Source

pub unsafe fn delegate( &self, ) -> Option<Retained<ProtocolObject<dyn AVAudioSessionDelegate>>>

👎Deprecated: No longer supported
Available on crate feature AVAudioSessionDeprecated only.
§Safety

This is not retained internally, you must ensure the object is still alive.

Source

pub unsafe fn setDelegate( &self, delegate: Option<&ProtocolObject<dyn AVAudioSessionDelegate>>, )

👎Deprecated: No longer supported
Available on crate feature AVAudioSessionDeprecated only.

Setter for delegate.

§Safety

This is unretained, you must ensure the object is kept alive while in use.

Source

pub unsafe fn setActive_withFlags_error( &self, active: bool, flags: NSInteger, ) -> Result<(), Retained<NSError>>

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn inputIsAvailable(&self) -> bool

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn currentHardwareSampleRate(&self) -> c_double

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn currentHardwareInputNumberOfChannels(&self) -> NSInteger

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn currentHardwareOutputNumberOfChannels(&self) -> NSInteger

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn setPreferredHardwareSampleRate_error( &self, sample_rate: c_double, ) -> Result<(), Retained<NSError>>

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.
Source

pub unsafe fn preferredHardwareSampleRate(&self) -> c_double

👎Deprecated
Available on crate feature AVAudioSessionDeprecated only.

Methods from Deref<Target = NSObject>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

pub fn class(&self) -> &'static AnyClass

Dynamically find the class of this object.

§Panics

May panic if the object is invalid (which may be the case for objects returned from unavailable init/new methods).

§Example

Check that an instance of NSObject has the precise class NSObject.

use objc2::ClassType;
use objc2::runtime::NSObject;

let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use Ivar::load instead.

Use Ivar::load instead.

§Safety

The object must have an instance variable with the given name, and it must be of type T.

See Ivar::load_ptr for details surrounding this.

Source

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: DowncastTarget,

Attempt to downcast the object to a class of type T.

This is the reference-variant. Use Retained::downcast if you want to convert a retained object to another type.

§Mutable classes

Some classes have immutable and mutable variants, such as NSString and NSMutableString.

When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.

So using this method to convert a NSString to a NSMutableString, while not unsound, is generally frowned upon unless you created the string yourself, or the API explicitly documents the string to be mutable.

See Apple’s documentation on mutability and on isKindOfClass: for more details.

§Generic classes

Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.

You can, however, safely downcast to generic collections where all the type-parameters are AnyObject.

§Panics

This works internally by calling isKindOfClass:. That means that the object must have the instance method of that name, and an exception will be thrown (if CoreFoundation is linked) or the process will abort if that is not the case. In the vast majority of cases, you don’t need to worry about this, since both root objects NSObject and NSProxy implement this method.

§Examples

Cast an NSString back and forth from NSObject.

use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};

let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();

Try (and fail) to cast an NSObject to an NSString.

use objc2_foundation::{NSObject, NSString};

let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());

Try to cast to an array of strings.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();

This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.

Downcast when processing each element instead.

use objc2_foundation::{NSArray, NSObject, NSString};

let arr = NSArray::from_retained_slice(&[NSObject::new()]);

for elem in arr {
    if let Some(data) = elem.downcast_ref::<NSString>() {
        // handle `data`
    }
}

Trait Implementations§

Source§

impl AsRef<AVAudioSession> for AVAudioSession

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<AnyObject> for AVAudioSession

Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for AVAudioSession

Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for AVAudioSession

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for AVAudioSession

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for AVAudioSession

Source§

const NAME: &'static str = "AVAudioSession"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = NSObject

The superclass of this class. Read more
Source§

type ThreadKind = <<AVAudioSession as ClassType>::Super as ClassType>::ThreadKind

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for AVAudioSession

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for AVAudioSession

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Hash for AVAudioSession

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for AVAudioSession

Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for AVAudioSession

Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for AVAudioSession

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for AVAudioSession

Source§

const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl DowncastTarget for AVAudioSession

Source§

impl Eq for AVAudioSession

Source§

impl Send for AVAudioSession

Source§

impl Sync for AVAudioSession

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

fn alloc() -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,