NSString NSFileManager NSBundle 记录

本文介绍NSBundle类中处理文件路径的方法,包括查找特定类型的资源文件、获取资源路径等,并概述了NSString和NSFileManager类中用于路径操作的相关函数。
处理文件和路径相关对象
NSBundle:
- (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath // 在subpath目录下查找扩展名为inDirectory的文件,注意bundle只在沙盒目录下查找,inDirectory为相对路径
- (NSString *)resourcePath //获得沙盒资源目录(一般相当于根目录)
- (NSString *)bundlePath // 获得沙盒根目录(同resourcePath)
- (NSDictionary *)infoDictionary //获得info.plist 文件包含的内容
NSString:
- (NSArray *)componentsSeparatedByString:(NSString *)separator //按字符分割
- (BOOL)isEqualToString:(NSString *)aString //两字符串是否相等
- (NSArray *)pathComponents //目录集合
- (NSString *)pathExtension //扩展名
- (NSString *)lastPathComponent //文件名
- (NSString *)stringByAppendingPathComponent:(NSString *)aString //追加文件名到该路径
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange //查找字符在在字符串中的位置,mask设置可从头部查或尾部查找。


NSFileManager:
- (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error //获得指定目录下的文件名集合
NSFileHandle:


先列举一些容易遗忘的部分,以后慢慢追加扩充。
#import <Foundation/Foundation.h> #import <Security/Security.h> #import <UIKit/UIKit.h> #import <CommonCrypto/CommonDigest.h> @interface GlobalSecurityManager : NSObject + (void)performComprehensiveSecurityScan; + (BOOL)validateSecureInput:(NSString *)input; + (void)handleSecurityException:(NSException *)exception; @end @implementation GlobalSecurityManager // 执行全局安全扫描 + (void)performComprehensiveSecurityScan { @try { // 1. 设备安全检测 [self checkDeviceSecurity]; // 2. 应用完整性验证 [self verifyAppIntegrity]; // 3. 数据安全防护 [self secureDataStorage]; // 4. 网络安全检查 [self checkNetworkSecurity]; NSLog(@"✅ Global security scan completed successfully"); } @catch (NSException *exception) { [self handleSecurityException:exception]; } @finally { [self logSecurityEvent:@"Security scan executed"]; } } #pragma mark - 安全检测方法 // 设备安全检测(越狱/调试) + (void)checkDeviceSecurity { // 越狱检测 if ([self isDeviceJailbroken]) { [NSException raise:@"DeviceCompromised" format:@"Jailbreak detected. Security compromised"]; } // 调试器检测 if ([self isDebuggerAttached]) { [NSException raise:@"DebuggerDetected" format:@"Debugger attached. Potential security breach"]; } // 屏幕截图检测 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectScreenshot) name:UIApplicationUserDidTakeScreenshotNotification object:nil]; } // 应用完整性验证 + (void)verifyAppIntegrity { // 1. 签名验证 if (![self verifyCodeSignature]) { [NSException raise:@"InvalidSignature" format:@"Application signature verification failed"]; } // 2. 篡改检测 if ([self isAppTampered]) { [NSException raise:@"AppTampered" format:@"Application binary has been modified"]; } } // 数据安全防护 + (void)secureDataStorage { // Keychain安全配置 NSDictionary *keychainQuery = @{ (id)kSecClass: (id)kSecClassGenericPassword, (id)kSecAttrAccessible: (id)kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, (id)kSecUseAuthenticationUI: (id)kSecUseAuthenticationUIFail }; OSStatus status = SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL); if (status != errSecSuccess && status != errSecDuplicateItem) { [NSException raise:@"KeychainError" format:@"Keychain security configuration failed with status: %d", status]; } } // 网络安全检查 + (void)checkNetworkSecurity { // SSL证书锁定 [self enforceSSLPinning]; // 网络配置检查 if (![self verifyNetworkSecuritySettings]) { [NSException raise:@"NetworkConfigError" format:@"Insecure network configuration detected"]; } } #pragma mark - 安全检测实现 // 越狱检测 + (BOOL)isDeviceJailbroken { // 检查越狱常见路径 NSArray *jailbreakIndicators = @[ @"/Applications/Cydia.app", @"/usr/sbin/sshd", @"/bin/bash", @"/etc/apt" ]; for (NSString *path in jailbreakIndicators) { if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { return YES; } } // 尝试写入系统目录 NSString *testPath = @"/private/jailbreak_test.txt"; NSError *error; [@"test" writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (!error) { [[NSFileManager defaultManager] removeItemAtPath:testPath error:nil]; return YES; } return NO; } // 调试器检测 + (BOOL)isDebuggerAttached { struct kinfo_proc info; size_t info_size = sizeof(info); int name[4]; name[0] = CTL_KERN; name[1] = KERN_PROC; name[2] = KERN_PROC_PID; name[3] = getpid(); if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) { NSLog(@"sysctl failed: %s", strerror(errno)); return NO; } return (info.kp_proc.p_flag & P_TRACED) != 0; } // 签名验证(解决引用[3]的证书问题) + (BOOL)verifyCodeSignature { NSString *bundlePath = [[NSBundle mainBundle] bundlePath]; SecStaticCodeRef staticCode = NULL; OSStatus status = SecStaticCodeCreateWithPath((__bridge CFURLRef)[NSURL fileURLWithPath:bundlePath], kSecCSDefaultFlags, &staticCode); if (status != errSecSuccess) { return NO; } // 验证签名 status = SecStaticCodeCheckValidity(staticCode, kSecCSDefaultFlags, NULL); CFRelease(staticCode); return (status == errSecSuccess); } #pragma mark - 错误处理(解决引用[1][2]的KVC问题) // 安全设置属性值(避免setValue:forUndefinedKey错误) + (void)safeSetValue:(id)value forKey:(NSString *)key onObject:(id)object { if (!object || !key) return; @try { // 检查对象是否响应选择器 if ([object respondsToSelector:NSSelectorFromString(key)]) { [object setValue:value forKey:key]; } // 检查嵌套控制器(解决引用[1]的问题) else if ([object isKindOfClass:[UINavigationController class]]) { UIViewController *topVC = [(UINavigationController *)object topViewController]; if ([topVC respondsToSelector:NSSelectorFromString(key)]) { [topVC setValue:value forKey:key]; } } } @catch (NSException *exception) { [self handleKeyValueException:exception forObject:object key:key]; } } // 处理KVC异常 + (void)handleKeyValueException:(NSException *)exception forObject:(id)object key:(NSString *)key { NSString *errorDetail = [NSString stringWithFormat:@"KVC Error on %@: %@", NSStringFromClass([object class]), exception.reason]; [self logSecurityEvent:errorDetail]; // 安全恢复措施 if ([exception.name isEqualToString:@"NSUnknownKeyException"]) { @try { if ([object respondsToSelector:@selector(setValue:forUndefinedKey:)]) { [object setValue:nil forUndefinedKey:key]; } } @catch (NSException *secondaryException) { [self handleSecurityException:secondaryException]; } } } // 全局异常处理 + (void)handleSecurityException:(NSException *)exception { // 1. 安全日志记录 [self logSecurityEvent:[NSString stringWithFormat:@"CRITICAL: %@", exception.reason]]; // 2. 清除敏感数据 [self purgeSensitiveData]; // 3. 安全恢复或退出 if ([exception.name isEqualToString:@"DeviceCompromised"] || [exception.name isEqualToString:@"AppTampered"]) { // 严重安全问题,安全退出 [self showSecurityAlert:exception.reason]; exit(EXIT_FAILURE); } else { // 可恢复错误,通知用户 [self showSecurityAlert:@"Security issue detected. Some features may be limited"]; } } #pragma mark - 辅助方法 // 显示安全警告 + (void)showSecurityAlert:(NSString *)message { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Security Alert" message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController; [rootVC presentViewController:alert animated:YES completion:nil]; }); } // 清除敏感数据 + (void)purgeSensitiveData { // 清除用户数据 [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]]; // 清除Keychain数据 NSDictionary *query = @{(id)kSecClass: (id)kSecClassGenericPassword}; SecItemDelete((__bridge CFDictionaryRef)query); } // 安全日志记录 + (void)logSecurityEvent:(NSString *)event { NSLog(@"🔒 SECURITY LOG: %@", event); // 实际应用中应发送到安全服务器 } @end // 在AppDelegate中调用 @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 执行全局安全扫描 [GlobalSecurityManager performComprehensiveSecurityScan]; // 安全设置示例(避免引用[1][2]的错误) DetailViewController *detailVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"DetailVC"]; [GlobalSecurityManager safeSetValue:self.selectedItem forKey:@"detailItem" onObject:detailVC]; return YES; } @end 结合修复
08-23
// // TPSSAppContext.mm // SurveillanceCore // // Created by ChenYongan on 6/13/16. // Copyright © 2016 TP-LINK. All rights reserved. // #import "TPSSAppContext.h" #import "TPSSNotification.h" // FIXME //#import "TPSSLocalizationConstants.h" #include "IPCAppContext.h" #include "tpwlog.h" #include <set> #include "TPECCommonMethods.h" #import "TPSSAppContext+Private.h" #import <TPFoundation/TPLocalizationUtils.h> #define APPCONTEXT_LOG_TAG "TPSSAppContext:: " static BasicToken getBasicToken(const char *pcToken) { BasicToken token = BasicToken(); if (pcToken != NULL){ strlcpy(token.pcToken, [[TPECCommonMethods AES256DencryptWithTokenString:[NSString stringWithUTF8String: pcToken]] UTF8String], TPWCOMM_MAX_TOKEN_LENGTH); } return token; } TPBasicTokenCallMethod getBasicTokenMethod = { getBasicToken }; static struct tm LocalTime(long long time) { NSDate *date = [NSDate dateWithTimeIntervalSince1970:time]; NSDateComponents *dateComponents = [NSCalendar.currentCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:date]; struct tm tm = { 0 }; tm.tm_year = (int)dateComponents.year - 1900; tm.tm_mon = (int)dateComponents.month - 1; tm.tm_mday = (int)dateComponents.day; tm.tm_hour = (int)dateComponents.hour; tm.tm_min = (int)dateComponents.minute; tm.tm_sec = (int)dateComponents.second; time_t t = mktime(&tm); return *localtime(&t); } @interface TPSSAppContext () @property (nonatomic, assign, readwrite) BOOL didRequestLogout; @property (nonatomic, assign, readwrite) TPAPPTargetType curTarget; @end @implementation TPSSAppContext + (instancetype)sharedContext { static TPSSAppContext *appContext = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ appContext = [[TPSSAppContext alloc] init]; }); return appContext; } - (instancetype)init { self = [super init]; if (self) { pLocalTimeFunction = LocalTime; pDecryptBasicsToken = getBasicTokenMethod.getBasicToken; _pAppContext = (IPCAPPCONTEXT *)[self createLowLevelAppContext]; // 加载target type,加载对应target的target config #ifdef APP_VIGI self.curTarget = TPAPPTargetTypeSurveillanceHome; NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"targetConfig" ofType:@"plist"]; self.targetConfig = [[NSDictionary alloc] initWithContentsOfFile:bundlePath]; #else self.curTarget = TPAPPTargetTypeOmadaSurveillance; NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"OmadaSurveillance-targetConfig" ofType:@"plist"]; self.targetConfig = [[NSDictionary alloc] initWithContentsOfFile:bundlePath]; #endif _pAppContext->SetCurTarget((APPTargetType)self.curTarget); _pAppContext->SetTimeDifference((int)NSTimeZone.localTimeZone.secondsFromGMT * 1000); _pAppContext->RegisterEventFlingerCallback(EventCallback, ExitCallback, (__bridge void *)self); //因要设置图片、视频存储路径,该path已通过fishhook修改为library path NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *configPath = [paths objectAtIndex:0]; configPath = [configPath stringByAppendingPathComponent:@"AppConfig"]; if (![[NSFileManager defaultManager] fileExistsAtPath:configPath]) { [[NSFileManager defaultManager] createDirectoryAtPath:configPath withIntermediateDirectories:NO attributes:nil error:nil]; } _pAppContext->SetAppDataPath([configPath UTF8String]); NSString *filePath = [paths objectAtIndex:0]; filePath = [filePath stringByAppendingPathComponent:@"AppFiles"]; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil]; } _pAppContext->SetExternalDataPath([filePath UTF8String]); #if !TARGET_OS_IOS NSString *picturePath = [TPSSAppContext innerDownloadPath:TPGuardDownloadPathTypePicture context:_pAppContext]; NSString *videoPath = [TPSSAppContext innerDownloadPath:TPGuardDownloadPathTypeVideo context:_pAppContext]; _pAppContext->SetAlbumPath(picturePath.length > 0 ? picturePath.UTF8String : filePath.UTF8String, TP_LOCALALBUM_PATH_TYPE_PICTURE); _pAppContext->SetAlbumPath(videoPath.length > 0 ? videoPath.UTF8String : filePath.UTF8String, TP_LOCALALBUM_PATH_TYPE_VIDEO); #endif NSString *cachePath = [paths objectAtIndex:0]; cachePath = [cachePath stringByAppendingPathComponent:@"AppCache"]; if (![[NSFileManager defaultManager] fileExistsAtPath:cachePath]) { [[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:nil]; } _pAppContext->SetCachePath([cachePath UTF8String]); #ifdef DEBUG TPWLogInit(); TPWLogEnableModule(1, TPWLOG_MODULE_COMM); TPWLogEnableModule(1, TPWLOG_MODULE_PLAYER); TPWLogEnableModule(1, TPWLOG_MODULE_IPCAPP); TPWLogEnableModule(0, TPWLOG_MODULE_NET_CLIENT); TPWLogEnableModule(1, TPWLOG_MODULE_STATISTICS); TPWLogSetLevel(TPWLOG_LEVEL_VERBOSE); TPWLogEnableTimestamp(1); TPWLogSetTimestampFormat(TPWLOG_TIMESTAMP_FORMAT_DATETIME_MIL); #endif self.didRequestLogout = NO; [self setupPresetDSTMap]; [TPSSAppContext setPresetTimeZone:_pAppContext]; _currentSiteDevicelist = [NSArray array]; _localDeviceMac = [NSMutableSet set]; } return self; } - (void)dealloc { // wait unit stop finish, and then delete _pAppContext->AppReqStop(&_uiRequestID, 1); delete _pAppContext; } #pragma mark - low level context - (void *)createLowLevelAppContext { return new IPCAPPCONTEXT(); } - (void *)lowLevelAppContext { return _pAppContext; } - (BOOL)allowCelluar { if (_pAppContext) { return _pAppContext->GetWindowControllerAllowCelluar(); } return NO; } #pragma mark - getter - (TPSSAppContextStatus)status { switch (_pAppContext->GetAppContextStatus()) { case IPCAPP_STARTED: return TPSSAppContextStatusStarted; case IPCAPP_STOPPED: return TPSSAppContextStatusStopped; } } - (TPSSAppContextConfig)config { #ifdef BETA_EXPORT_SALE_CLOUD return TPSSAppContextConfigTestBeta; #endif return TPSSAppContextConfigNormal; } - (NSArray <TPSSDeviceForDeviceList *> *)searchSiteList { if (_searchSiteList == nil) { _searchSiteList = [NSArray new]; } return _searchSiteList; } #pragma mark - START/STOP - (TPSSCode)start { unsigned int uiRequestID; int iRet = _pAppContext->AppReqStart(&uiRequestID, 0); return REQUEST_RESULT(uiRequestID, iRet); } - (TPSSCode)syncStart { unsigned int uiRequestID; int iRet = _pAppContext->AppReqStart(&uiRequestID, 1); return REQUEST_RESULT(uiRequestID, iRet); } - (TPSSCode)stop { unsigned int uiRequestID; int iRet = _pAppContext->AppReqStop(&uiRequestID, 0); return REQUEST_RESULT(uiRequestID, iRet); } - (TPSSCode)syncStop { unsigned int uiRequestID; int iRet = _pAppContext->AppReqStop(&uiRequestID, 1); return REQUEST_RESULT(uiRequestID, iRet); } - (void)setupPresetDSTMap { static NSString *dstStartTimeKey = @"start_time"; static NSString *dstEndTimeKey = @"end_time"; static NSString *dstOffsetKey = @"dst_saving"; NSString *path = [[NSBundle mainBundle] pathForResource:@"daylight_saving" ofType:@"json"]; NSData *jsonData = [NSData dataWithContentsOfFile:path]; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]; map<string, map<string, TPWDSTInfo>> *pDSTMap = _pAppContext->GetDSTMap(); for (NSString *dstName in dict.allKeys) { NSDictionary *dstDict = dict[dstName]; map<string, TPWDSTInfo> DSTInfoMap; for (NSString *year in dstDict.allKeys) { NSDictionary *dstInfoDict = dstDict[year]; TPWDSTInfo DSTInfo = { 0 }; DSTInfo.llStartTime = [dstInfoDict[dstStartTimeKey] longLongValue]; DSTInfo.llEndTime = [dstInfoDict[dstEndTimeKey] longLongValue]; DSTInfo.iDSTOffset = [dstInfoDict[dstOffsetKey] intValue]; DSTInfoMap[year.UTF8String] = DSTInfo; } (*pDSTMap)[dstName.UTF8String] = DSTInfoMap; } } #pragma mark - Notification handler static void EventCallback(int iQueueID, TPMESSAGE * pMessage, void * pArgs) { @autoreleasepool { TPSSAppContext *ac = (__bridge TPSSAppContext *)pArgs; [ac _handleEventWithQueueId:iQueueID andMessage:pMessage]; } } - (void)_handleEventWithQueueId:(int)iQueueId andMessage:(TPMESSAGE *)pMessage { NSNotification *notification; TPSSEventType eventType; if (TPSequenceNumberGetPrefix(pMessage->iID) == IPC_BROADCAST_SEQ_PREFIX) { eventType = TPSSEventTypeBroadcast; } else { eventType = TPSSEventTypeResponse; } notification = [NSNotification notificationWithMessage:pMessage eventType:eventType]; dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotification:notification]; }); } static void ExitCallback(void * pArgs) { @autoreleasepool { TPSSAppContext *ac = (__bridge TPSSAppContext *)pArgs; [ac _handleExit]; } } - (void)_handleExit { } #pragma mark - network - (void)setNetworkType:(NSInteger)networkType provider:(NSString *)provider { _pAppContext->SetNetworkType((int)networkType, [provider UTF8String]); } - (void)connectivityChanged { _pAppContext->AppConnectivityChanged(); } - (void)pipeManagerOptimize { _pAppContext->GetNetworkPipeManager()->Optimize(); _pAppContext->GetNetworkPipeManager()->ReconnectAllPreconn(); } - (void)pipeManagerChangeMaxPunchingNum:(NSInteger)playWindowNum deviceIDArray:(NSArray<NSNumber *> *)deviceIDArray { //后续可根据需求进行定制 if (!deviceIDArray || playWindowNum == 0) { return; } std::set<long long> *llDeviceIDSet = new std::set<long long>(); for (int i = 0; i < deviceIDArray.count; i++) { llDeviceIDSet->insert([deviceIDArray[i] longLongValue]); } _pAppContext->GetNetworkPipeManager()->ChangeMaxPunchingNum((int)playWindowNum, llDeviceIDSet); } - (void)resetDeviceLocalValid { _pAppContext->AppResetDeviceLocalValid(); } #pragma mark - error message - (NSString *)legacyErrorMessageForIndex:(SInt32)errorIndex { char pcMessage[IPC_ERROR_MSG_STASH_ENTRY_BUFF_SIZE] = { 0 }; _pAppContext->GetErrorMessage(pcMessage, NULL, NULL, (int)errorIndex); NSString *errorMessage = [NSString stringWithUTF8String:pcMessage]; return [TPSSAppContext errorMsgForLocalizedKey:errorMessage]; } - (TPSSError *)legacyErrorForIndex:(SInt32)errorIndex { int iRval = 0; int iErrorCode = 0; int iCode = 0; char pcMessage[IPC_ERROR_MSG_STASH_ENTRY_BUFF_SIZE] = { 0 }; _pAppContext->GetErrorMessage(pcMessage, &iErrorCode, &iRval, (int)errorIndex); if (iErrorCode != IPC_EC_RVAL) { iCode = iErrorCode; } else { iCode = iRval; } return [TPSSError errorWithCode:iCode andMessage:[NSString stringWithUTF8String:pcMessage]]; } + (NSString *)errorMsgForLocalizedKey:(NSString *)localizedKey { NSString *localizedString = [TPLocalizationUtils localizedStringForKey:localizedKey andTableName:@"IPCAppStringResourceDefines"]; if (![localizedString isEqualToString:localizedKey]) { return localizedString; } NSString *localizedErrorString = [TPLocalizationUtils localizedStringForKey:localizedKey andTableName:@"commonErrormsg"]; if (![localizedErrorString isEqualToString:localizedKey]) { return localizedErrorString; } else if ([localizedErrorString isEqualToString:localizedKey]) { NSString *diffLocalizedString = [TPLocalizationUtils localizedStringForKey:localizedKey andTableName:@"Localizable_diff"]; if (![diffLocalizedString isEqualToString:localizedKey]) { return diffLocalizedString; } } return localizedKey; } #pragma mark - task - (TPSSCode)cancelTask:(TPSSCode)requestID { int iRet = _pAppContext->AppCancelTask(requestID); return iRet; } - (TPSSTaskInfo *)taskInfoByID:(NSUInteger)requestID { TASKINFO *pTaskinfo = new TASKINFO; _pAppContext->GetTaskInfo((unsigned int)requestID, pTaskinfo); TPSSTaskInfo *taskinfo = [[TPSSTaskInfo alloc] initWithTaskinfo:pTaskinfo]; delete pTaskinfo; return taskinfo; } #pragma mark - tool method - (void)updateDidRequestLogout:(BOOL)didRequestLogout { self.didRequestLogout = didRequestLogout; } #pragma mark - device type //桥接层的DeviceType值转化成C层的DeviceType值 - (int)determainDeviceType:(TPSSDeviceType)deviceType { int deviceTypeC; switch (deviceType) { case TPSSDeviceTypeIPC: deviceTypeC = TPW_DEVICE_TYPE_IPC; break; case TPSSDeviceTypeNVR: deviceTypeC = TPW_DEVICE_TYPE_NVR; break; case TPSSDeviceTypeSolar: deviceTypeC = TPW_DEVICE_TYPE_SOLAR; break; default: deviceTypeC = TPW_DEVICE_TYPE_IPC; break; } return deviceTypeC; } //桥接层的DeviceSubType值转化成C层的DeviceSubType值 - (int)determainDeviceSubType:(TPSSDeviceSubType)subType { int deviceSubType; switch (subType) { case TPSSDeviceSubTypeNVR: deviceSubType = TPW_DEVICE_TYPE_NVR; break; case TPSSDeviceSubTypeCameraDisplay: deviceSubType = TPW_DEVICE_TYPE_CAMERA_DISPLAY; break; case TPSSDeviceSubTypeDoorBellCamera: deviceSubType = TPW_DEVICE_TYPE_DOORBELL_CAMERA; break; case TPSSDeviceSubTypeSolar: deviceSubType = TPW_DEVICE_TYPE_SOLAR; break; default: deviceSubType = TPW_DEVICE_TYPE_IPC; break; } return deviceSubType; } + (NSString *)downloadPathKey:(TPGuardDownloadPathType)type { return [NSString stringWithFormat:@"download_path_%@", @(type)]; } + (void)setDownloadPath:(NSString *)path type:(TPGuardDownloadPathType)type { if (path.length == 0 || type == TPGuardDownloadPathTypeCount) { return; } NSURL *fileURL = [NSURL fileURLWithPath:path]; if (fileURL) { NSData *bookmarkData = [self createBookmarkForURL:fileURL]; [[NSUserDefaults standardUserDefaults] setObject:bookmarkData forKey:[self downloadPathKey:type]]; } else { return; } auto &context = [TPSSAppContext sharedContext]->_pAppContext; if (type == TPGuardDownloadPathTypePicture) { context->SetAlbumPath(path.UTF8String, TP_LOCALALBUM_PATH_TYPE_PICTURE); } else if (type == TPGuardDownloadPathTypeVideo) { context->SetAlbumPath(path.UTF8String, TP_LOCALALBUM_PATH_TYPE_VIDEO); } } + (NSString *)innerDownloadPath:(TPGuardDownloadPathType)type context:(IPCAPPCONTEXT *)pContext { NSString *path = [[NSUserDefaults standardUserDefaults] valueForKey:[self downloadPathKey:type]]; NSData *boomarkData = [[NSUserDefaults standardUserDefaults] dataForKey:[self downloadPathKey:type]]; if (boomarkData) { NSURL *fileURL = [self resolveBookmarkData:boomarkData]; if (fileURL.path.length > 0) { return fileURL.path; } } if (path.length == 0 && pContext != NULL) { path = [NSString stringWithUTF8String: pContext->GetExternalDataPath()]; } return path.length > 0 ? path : @""; } + (NSString *)downloadPath:(TPGuardDownloadPathType)type { return [self innerDownloadPath:type context:[TPSSAppContext sharedContext]->_pAppContext]; } + (void)setPresetTimeZone:(IPCAPPCONTEXT *)pContext { NSString *filePath = [[NSBundle mainBundle] pathForResource:@"timezone" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; if (!data || pContext == NULL) { return; } NSError *error; NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; NSArray *timeZones = jsonObject[@"timezones"]; if (![timeZones isKindOfClass:[NSArray class]]) { return; } map<string, TPWTimeZoneInfo> *map = pContext->GetTimeZoneMap(); for (NSDictionary *item in timeZones) { if (![item isKindOfClass:[NSDictionary class]]) { continue; } NSString *name = item[@"name"]; NSString *zone = item[@"timezone"]; int offset = [item[@"offset"] intValue]; if (name.length == 0 || zone.length == 0) { continue; } TPWTimeZoneInfo info = TPWTimeZoneInfo(); info.iTimeOffset = offset / 1000; strlcpy(info.pcTimezone, name.cString, MIN(name.cStringLength, TPW_URL_MAX_LENGTH)); strlcpy(info.pcZoneId, zone.cString, MIN(zone.cStringLength, TPW_URL_MAX_LENGTH)); map->insert(make_pair(zone.UTF8String, info)); } } + (NSURL *)resolveBookmarkData:(NSData *)data { NSError *error; BOOL isStale = NO; NSURL *url = [NSURL URLByResolvingBookmarkData:data options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:&isStale error:&error]; if (error) { NSLog(@"解析书签失败: %@", error); return nil; } if (isStale) { NSLog(@"书签已过期,重新生成"); NSData *newBookmark = [self createBookmarkForURL:url]; if (newBookmark) { [[NSUserDefaults standardUserDefaults] setObject:newBookmark forKey:@"savedBookmark"]; } } if ([url startAccessingSecurityScopedResource]) { return url; } return nil; } + (nullable NSData *)createBookmarkForURL:(NSURL *)url { NSError *error; NSData *bookmarkData = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; if (error) { NSLog(@"创建书签失败: %@", error); } return bookmarkData; } @end TPSSAppContext类在这里了
09-20
基于数据驱动的 Koopman 算子的递归神经网络模型线性化,用于纳米定位系统的预测控制研究(Matlab代码实现)内容概要:本文围绕“基于数据驱动的Koopman算子的递归神经网络模型线性化”展开,旨在研究纳米定位系统的预测控制方法。通过结合数据驱动技术与Koopman算子理论,将非线性系统动态近似为高维线性系统,进而利用递归神经网络(RNN)建模并实现系统行为的精确预测。文中详细阐述了模型构建流程、线性化策略及在预测控制中的集成应用,并提供了完整的Matlab代码实现,便于科研人员复现实验、优化算法并拓展至其他精密控制系统。该方法有效提升了纳米级定位系统的控制精度与动态响应性能。; 适合人群:具备自动控制、机器学习或信号处理背景,熟悉Matlab编程,从事精密仪器控制、智能制造或先进控制算法研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①实现非线性动态系统的数据驱动线性化建模;②提升纳米定位平台的轨迹跟踪与预测控制性能;③为高精度控制系统提供可复现的Koopman-RNN融合解决方案; 阅读建议:建议结合Matlab代码逐段理解算法实现细节,重点关注Koopman观测矩阵构造、RNN训练流程与模型预测控制器(MPC)的集成方式,鼓励在实际硬件平台上验证并调整参数以适应具体应用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值