Сведения о памяти
Запросите актуальные сведения о памяти подключённого устройства, а затем прочитайте обновлённое свойство storageInfo.
Предварительные условия
Перед запросом сведений о памяти убедитесь, что:
- Устройство подключено и находится в стабильном состоянии.
- Устройство поддерживает протокол
DeviceInfoAPI.
Справочник API
Фреймворк
AIBuds.xcframework
Импорт
В файлах, где используется SDK, импортируйте основной фреймворк:
- Swift
- Objective-C
import AIBuds#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Метод запроса и свойство с результатом объявлены в DeviceInfoAPI.
- Swift
- Objective-C
protocol DeviceInfoAPI: DeviceAPI {
/// Device storage information.
var storageInfo: StorageInfoModel? { get }
/// Request to query the device storage information.
/// - Parameters:
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func requestQueryStorageInfo(
_ completion: AIBudsCompletionHandler?
)
}@protocol AIBudsDeviceInfoAPI <AIBudsDeviceAPI>
/// Device storage information.
@property(nonatomic, readonly, strong) AIBudsStorageInfoModel *_Nullable storageInfo;
/// Request to query the device storage information.
/// - Parameters:
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation
/// was successful.
- (void)requestQueryStorageInfoWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
@endМетод экземпляра
Запрашивает актуальные сведения о памяти устройства.
- Swift
- Objective-C
/// Request to query the device storage information.
/// - Parameters:
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func requestQueryStorageInfo(
_ completion: AIBudsCompletionHandler?
)/// Request to query the device storage information.
/// - Parameters:
/// - completion: A closure that is called when the operation completes.
/// - success: `true` if the operation was successful; otherwise `false`.
/// - error: An `NSError` object that describes the error that occurred, or `nil` if the operation
/// was successful.
- (void)requestQueryStorageInfoWithCompletion:(AIBudsCompletionHandler _Nullable)completion;Параметры
| Параметр | Тип | Описание |
|---|---|---|
completion | AIBudsCompletionHandler? | Необязательный обработчик, вызываемый после завершения запроса. |
Параметры обратного вызова:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | true, если запрос выполнен успешно; иначе false. |
error | NSError? | Сведения об ошибке при неудачном запросе; иначе nil. |
Свойства результата:
| Свойство | Тип | Описание |
|---|---|---|
usedSpaceInMB | NSNumber | Использованное пространство в мегабайтах. |
freeSpaceInMB | NSNumber | Оставшееся свободное пространство в мегабайтах. |
Возвращаемое значение
Обработчик завершения не возвращает сведения о памяти. После успешного запроса прочитайте обновлённое свойство storageInfo.
Примеры использования
- Swift
- Objective-C
import AIBuds
final class DeviceManager {
weak var device: DeviceConvertible?
func queryStorageInformation() {
guard let device = device as? DeviceInfoAPI else {
print("Device does not support storage queries")
return
}
device.requestQueryStorageInfo { success, error in
guard success else {
print("Storage query failed: \(error?.localizedDescription ?? "Unknown error")")
return
}
guard let storage = device.storageInfo else {
print("The device did not provide storage information")
return
}
print("Used storage: \(storage.usedSpaceInMB) MB")
print("Free storage: \(storage.freeSpaceInMB) MB")
}
}
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
@interface DeviceManager ()
@property(weak, nonatomic) id<AIBudsDeviceConvertible> device;
@end
@implementation DeviceManager
- (void)queryStorageInformation {
id<AIBudsDeviceInfoAPI> device = (id<AIBudsDeviceInfoAPI>)self.device;
if (![device conformsToProtocol:@protocol(AIBudsDeviceInfoAPI)]) {
NSLog(@"Device does not support storage queries");
return;
}
[device requestQueryStorageInfoWithCompletion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Storage query failed: %@", error.localizedDescription ?: @"Unknown error");
return;
}
AIBudsStorageInfoModel *storage = device.storageInfo;
if (!storage) {
NSLog(@"The device did not provide storage information");
return;
}
NSLog(@"Used storage: %@ MB", storage.usedSpaceInMB);
NSLog(@"Free storage: %@ MB", storage.freeSpaceInMB);
}];
}
@endОбработка ошибок
- Прежде чем читать обновлённое свойство, проверьте
success. - Если запрос не выполнен, сведения о причине доступны в
error. - Учитывайте значение
nilдляstorageInfoдаже после успешного обратного вызова. - Не полагайтесь на фиксированные коды ошибок, если они не задокументированы для конкретного устройства.
Рекомендации
- Читайте после успешного запроса: обращайтесь к
storageInfoтолько после успешного завершения запроса. - Соблюдайте единицы SDK: оба значения указаны в мегабайтах, а не в байтах.
- Проверяйте соответствие протоколу: убедитесь, что устройство поддерживает
DeviceInfoAPI. - Обновляйте UI в главной очереди: выполняйте вызванные завершением обновления UIKit в главной очереди.
Примечания
- Обработчик завершения сообщает состояние запроса, но не содержит результат
StorageInfoModel. StorageInfoModelпредоставляет только занятое и свободное пространство в мегабайтах.- В этой модели SDK не предоставляет отдельное свойство общей ёмкости.
- Сведения о памяти могут меняться во время записи, импорта или удаления медиафайлов.