小游戏房可以连接成功了

This commit is contained in:
fengshuo
2022-02-14 19:29:29 +08:00
committed by chenguilong
parent 584697c874
commit 3a6e9d731b
84 changed files with 5857 additions and 52 deletions

View File

@@ -459,6 +459,14 @@
E8A6C2A227CF856E00AC7442 /* HomeCollectRoomModel.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A6C2A127CF856E00AC7442 /* HomeCollectRoomModel.m */; };
E8AA6EEF27DF1E6B009B4C2B /* XPRoomTopicViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E8AA6EEE27DF1E6B009B4C2B /* XPRoomTopicViewController.m */; };
E8AA6EF227DF1E97009B4C2B /* XPRoomTopicPresenter.m in Sources */ = {isa = PBXBuildFile; fileRef = E8AA6EF127DF1E97009B4C2B /* XPRoomTopicPresenter.m */; };
E8A86DF727BA2F1C001C21F9 /* XPRoomLittleGameContainerView.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86DF627BA2F1C001C21F9 /* XPRoomLittleGameContainerView.m */; };
E8A86E0427BA38DB001C21F9 /* SudCommon.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86DF927BA38DB001C21F9 /* SudCommon.m */; };
E8A86E0527BA38DB001C21F9 /* NSString+RW.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86DFC27BA38DB001C21F9 /* NSString+RW.m */; };
E8A86E0627BA38DB001C21F9 /* UIColor+RW.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86DFE27BA38DB001C21F9 /* UIColor+RW.m */; };
E8A86E0727BA38DB001C21F9 /* NSData+RW.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86DFF27BA38DB001C21F9 /* NSData+RW.m */; };
E8A86E0827BA38DB001C21F9 /* UIImage+RW.m in Sources */ = {isa = PBXBuildFile; fileRef = E8A86E0127BA38DB001C21F9 /* UIImage+RW.m */; };
E8A86E0D27BA6B71001C21F9 /* SudMGP.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = E8A86E0A27BA3943001C21F9 /* SudMGP.xcframework */; };
E8A86E0E27BA6B71001C21F9 /* SudMGP.xcframework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = E8A86E0A27BA3943001C21F9 /* SudMGP.xcframework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
E8AC721026F43955007D6E91 /* UIImageConstant.m in Sources */ = {isa = PBXBuildFile; fileRef = E8AC720F26F43955007D6E91 /* UIImageConstant.m */; };
E8AC721326F46ADD007D6E91 /* XPMineSettingViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E8AC721226F46ADD007D6E91 /* XPMineSettingViewController.m */; };
E8AC721626F46B06007D6E91 /* XPMineSettingTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E8AC721526F46B06007D6E91 /* XPMineSettingTableViewCell.m */; };
@@ -602,6 +610,7 @@
18E7B25A26E8D4450064BC9B /* flutter_boost.xcframework in Embed Frameworks */,
184863482721715D005FC5DC /* ZegoAudioRoom.framework in Embed Frameworks */,
18E7B25826E8D4430064BC9B /* App.xcframework in Embed Frameworks */,
E8A86E0E27BA6B71001C21F9 /* SudMGP.xcframework in Embed Frameworks */,
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
@@ -1493,6 +1502,20 @@
E8AA6EF027DF1E97009B4C2B /* XPRoomTopicPresenter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = XPRoomTopicPresenter.h; sourceTree = "<group>"; };
E8AA6EF127DF1E97009B4C2B /* XPRoomTopicPresenter.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = XPRoomTopicPresenter.m; sourceTree = "<group>"; };
E8AA6EF327DF1EB6009B4C2B /* XPRoomTopicProtocol.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = XPRoomTopicProtocol.h; sourceTree = "<group>"; };
E8A86DF527BA2F1C001C21F9 /* XPRoomLittleGameContainerView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = XPRoomLittleGameContainerView.h; sourceTree = "<group>"; };
E8A86DF627BA2F1C001C21F9 /* XPRoomLittleGameContainerView.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = XPRoomLittleGameContainerView.m; sourceTree = "<group>"; };
E8A86DF927BA38DB001C21F9 /* SudCommon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SudCommon.m; sourceTree = "<group>"; };
E8A86DFA27BA38DB001C21F9 /* SudCommon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SudCommon.h; sourceTree = "<group>"; };
E8A86DFC27BA38DB001C21F9 /* NSString+RW.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+RW.m"; sourceTree = "<group>"; };
E8A86DFD27BA38DB001C21F9 /* UIImage+RW.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+RW.h"; sourceTree = "<group>"; };
E8A86DFE27BA38DB001C21F9 /* UIColor+RW.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIColor+RW.m"; sourceTree = "<group>"; };
E8A86DFF27BA38DB001C21F9 /* NSData+RW.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+RW.m"; sourceTree = "<group>"; };
E8A86E0027BA38DB001C21F9 /* NSString+RW.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+RW.h"; sourceTree = "<group>"; };
E8A86E0127BA38DB001C21F9 /* UIImage+RW.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+RW.m"; sourceTree = "<group>"; };
E8A86E0227BA38DB001C21F9 /* UIColor+RW.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIColor+RW.h"; sourceTree = "<group>"; };
E8A86E0327BA38DB001C21F9 /* NSData+RW.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+RW.h"; sourceTree = "<group>"; };
E8A86E0A27BA3943001C21F9 /* SudMGP.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = SudMGP.xcframework; sourceTree = "<group>"; };
E8A86E0C27BA3DF4001C21F9 /* SudGameConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SudGameConfig.h; sourceTree = "<group>"; };
E8AC720E26F43955007D6E91 /* UIImageConstant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = UIImageConstant.h; sourceTree = "<group>"; };
E8AC720F26F43955007D6E91 /* UIImageConstant.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = UIImageConstant.m; sourceTree = "<group>"; };
E8AC721126F46ADD007D6E91 /* XPMineSettingViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = XPMineSettingViewController.h; sourceTree = "<group>"; };
@@ -1749,6 +1772,7 @@
buildActionMask = 2147483647;
files = (
18E7B25B26E8D4460064BC9B /* Flutter.xcframework in Frameworks */,
E8A86E0D27BA6B71001C21F9 /* SudMGP.xcframework in Frameworks */,
186A52E526FC559200D67B2C /* AliyunOSSiOS.framework in Frameworks */,
73FFADDC93E195344047A2EC /* Pods_xplan_ios.framework in Frameworks */,
18E7B25F26E8D44B0064BC9B /* FMDB.xcframework in Frameworks */,
@@ -1825,6 +1849,7 @@
186A52D826FC551700D67B2C /* Library */ = {
isa = PBXGroup;
children = (
E8A86E0927BA3943001C21F9 /* SudMGPSDK */,
186A52D926FC558500D67B2C /* RPSDK */,
);
path = Library;
@@ -3149,6 +3174,7 @@
E81EF6E1279AB90E00FF3EDE /* Model */,
E81EF6E5279AC20D00FF3EDE /* Api */,
E8DBB6FE27B64FC700AA285D /* View */,
E8A86DF827BA38A5001C21F9 /* Presenter */,
);
path = LittleGame;
sourceTree = "<group>";
@@ -4149,6 +4175,40 @@
path = Sources;
sourceTree = "<group>";
};
E8A86DF827BA38A5001C21F9 /* Presenter */ = {
isa = PBXGroup;
children = (
E8A86DFB27BA38DB001C21F9 /* Category */,
E8A86E0C27BA3DF4001C21F9 /* SudGameConfig.h */,
E8A86DFA27BA38DB001C21F9 /* SudCommon.h */,
E8A86DF927BA38DB001C21F9 /* SudCommon.m */,
);
path = Presenter;
sourceTree = "<group>";
};
E8A86DFB27BA38DB001C21F9 /* Category */ = {
isa = PBXGroup;
children = (
E8A86DFC27BA38DB001C21F9 /* NSString+RW.m */,
E8A86DFD27BA38DB001C21F9 /* UIImage+RW.h */,
E8A86DFE27BA38DB001C21F9 /* UIColor+RW.m */,
E8A86DFF27BA38DB001C21F9 /* NSData+RW.m */,
E8A86E0027BA38DB001C21F9 /* NSString+RW.h */,
E8A86E0127BA38DB001C21F9 /* UIImage+RW.m */,
E8A86E0227BA38DB001C21F9 /* UIColor+RW.h */,
E8A86E0327BA38DB001C21F9 /* NSData+RW.h */,
);
path = Category;
sourceTree = "<group>";
};
E8A86E0927BA3943001C21F9 /* SudMGPSDK */ = {
isa = PBXGroup;
children = (
E8A86E0A27BA3943001C21F9 /* SudMGP.xcframework */,
);
path = SudMGPSDK;
sourceTree = "<group>";
};
E8AC720A26F435AF007D6E91 /* UIImageView */ = {
isa = PBXGroup;
children = (
@@ -4579,6 +4639,8 @@
E836DBCC279BF2F10056F7DD /* XPLittleGameRoomListView.m */,
E8DBB6FF27B6501200AA285D /* XPLittleGameMiniStageView.h */,
E8DBB70027B6501200AA285D /* XPLittleGameMiniStageView.m */,
E8A86DF527BA2F1C001C21F9 /* XPRoomLittleGameContainerView.h */,
E8A86DF627BA2F1C001C21F9 /* XPRoomLittleGameContainerView.m */,
);
path = View;
sourceTree = "<group>";
@@ -5045,6 +5107,7 @@
E81EF6E8279AC21E00FF3EDE /* Api+LittleGame.m in Sources */,
E8EEB91126FC6AE2007C6EBA /* XPMineUserInfoEditProtocol.h in Sources */,
180116FC279E8CCE00F2CBC0 /* NVDate.m in Sources */,
E8A86E0427BA38DB001C21F9 /* SudCommon.m in Sources */,
E8EEB90326FC31DC007C6EBA /* XPMineUserInfoProtocol.h in Sources */,
E8232603274E4AA0003A3332 /* ThemeColor+UserCard.m in Sources */,
E87A24F1272935920086A794 /* XPMessageRemoteExtModel.m in Sources */,
@@ -5154,6 +5217,7 @@
E8252FEE27687DF1002B3164 /* ActivityInfoModel.m in Sources */,
E84BF7D1277BFCDD00EF8877 /* RoomTagModel.m in Sources */,
E8AC723526F49939007D6E91 /* XPMineNotificaPresenter.m in Sources */,
E8A86E0727BA38DB001C21F9 /* NSData+RW.m in Sources */,
E80DE40A277568D300BE5BCB /* ThemeColor+FirstRecharge.m in Sources */,
9BC5C8ED277AFF63007C8719 /* XPNobleCenterViewController.m in Sources */,
9B92A34A2797F35E00AD168F /* XPMatchManageTableViewCell.m in Sources */,
@@ -5175,6 +5239,7 @@
E8E70D7A26F2F16600F03460 /* XPMinePresent.m in Sources */,
E8A1E45B27620F4900B294CA /* XPRoomHalfWebView.m in Sources */,
9B7D80562753C595003DAC0C /* SendMessageView.m in Sources */,
E8A86E0527BA38DB001C21F9 /* NSString+RW.m in Sources */,
E84B0E3F2727EDF6008818C6 /* XPRoomMessageTableViewCell.m in Sources */,
E8E5E18B27C332EE00F457D8 /* XPHomeViewController.m in Sources */,
E82325FC274E4735003A3332 /* XPUserCardItemModel.m in Sources */,
@@ -5296,6 +5361,7 @@
E8C1CD6A27D8937800376F83 /* XPRoomFaceCollectionViewCell.m in Sources */,
E8DBB6F927B639A300AA285D /* LittleGameStageView.m in Sources */,
E811FFF72742367B00918544 /* XPGiftEmptyCollectionViewCell.m in Sources */,
E8A86E0827BA38DB001C21F9 /* UIImage+RW.m in Sources */,
189DD67E26E1FD8900AB55B1 /* UIImage+Utils.m in Sources */,
E824545626F5E51900BE8163 /* XPMineVerifIdentityViewController.m in Sources */,
E82D5C73276AE94800858D6D /* CarModel.m in Sources */,
@@ -5322,6 +5388,7 @@
E8C6FFCB27548120004DC9F0 /* XPHomePartyViewController.m in Sources */,
E8680718271967B00024F48F /* MicroView.m in Sources */,
E896EF942771AAC100AD2CC1 /* XPMineFansPresenter.m in Sources */,
E8A86E0627BA38DB001C21F9 /* UIColor+RW.m in Sources */,
E8B825CD26EA18C8009E8E9F /* ThemeColor.m in Sources */,
E8A6C29F27CF5FE500AC7442 /* HomeLiveRoomModel.m in Sources */,
E84150B827747B8B00A7F548 /* XPFirstRechargeViewController.m in Sources */,
@@ -5392,6 +5459,7 @@
9B208A362779B50100F9E54A /* GiftNobleInfoModel.m in Sources */,
E8C6FFDA2754BE81004DC9F0 /* ThemeColor+Home.m in Sources */,
E824545126F5CE6E00BE8163 /* XPMineModifPayPwdPresenter.m in Sources */,
E8A86DF727BA2F1C001C21F9 /* XPRoomLittleGameContainerView.m in Sources */,
E880B3AF278BE1D800A83B0D /* Api+AcrossRoomPK.m in Sources */,
E8EEB90F26FC6AB8007C6EBA /* XPMineUserInfoEditPresenter.m in Sources */,
E8AC723A26F49AAE007D6E91 /* XPMineNotifyStatus.m in Sources */,

View File

@@ -106,7 +106,9 @@ NS_ASSUME_NONNULL_BEGIN
@property (nonatomic, copy) NSString *androidBubbleUrl;
///iOS房间公屏气泡
@property (nonatomic, copy) NSString *iosBubbleUrl;
#pragma mark - 小游戏
/// 小游戏状态 0 未加入游戏1 加入游戏未准备2 加入游戏已准备 3 游戏中
@property (nonatomic, assign) LittleGamePlayStatus gameStatus;
@end
NS_ASSUME_NONNULL_END

View File

@@ -33,6 +33,8 @@ typedef NS_ENUM(NSUInteger, KeyType) {
keyType_UMengAppKey,///友盟统计的key
keyType_UMengAppChannel,///友盟统计的渠道
KeyType_FacePwdEncode, ///表情包解密key
KeyType_SudGameAppID,///小游戏APPID
KeyType_SudGameAppKey,///小游戏APPKey
};
/// 获取当前项目中所用到的 type 所对应的 value 的值 type 类型

View File

@@ -45,6 +45,8 @@ NSString * const KeyWithType(KeyType type) {
@(keyType_UMengAppKey) : @"61b065e8e014255fcba606d1",
@(keyType_UMengAppChannel) : @"App Store",
@(KeyType_FacePwdEncode) : @"1ea53d260ecf11e7b56e00163e046a26",
@(KeyType_SudGameAppID) : @"1467745235064848385",
@(KeyType_SudGameAppKey) : @"BvjLDpWol7OihaYeFebuepx1bZu6cxU5"
},
///
@(NO):@{
@@ -62,6 +64,8 @@ NSString * const KeyWithType(KeyType type) {
@(keyType_UMengAppKey) : @"5ff6bc6dadb42d5826a1cbc4",
@(keyType_UMengAppChannel) : @"App Store",
@(KeyType_FacePwdEncode) : @"1ea53d260ecf11e7b56e00163e046a26",
@(KeyType_SudGameAppID) : @"1467745235064848385",
@(KeyType_SudGameAppKey) : @"BvjLDpWol7OihaYeFebuepx1bZu6cxU5"
}
};
NSDictionary * enviroDic = [dic objectForKey:@(isRelase)];

View File

@@ -53,4 +53,11 @@ typedef NS_ENUM(NSInteger, UserEnterRoomFromType) {
///跨房PK
UserEnterRoomFromType_Cross_Room_PK = 9
};
typedef NS_ENUM(NSInteger, LittleGamePlayStatus) {
LittleGamePlayStatus_NoIn = 0,//未加入
LittleGamePlayStatus_IsIn = 1,//已加入
LittleGamePlayStatus_Ready = 2, //已准备
LittleGamePlayStatus_Plying = 3,//游戏中
};
#endif /* XPEnum_h */

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>AvailableLibraries</key>
<array>
<dict>
<key>LibraryIdentifier</key>
<string>ios-arm64_armv7</string>
<key>LibraryPath</key>
<string>SudMGP.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>arm64</string>
<string>armv7</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
</dict>
<dict>
<key>LibraryIdentifier</key>
<string>ios-x86_64-simulator</string>
<key>LibraryPath</key>
<string>SudMGP.framework</string>
<key>SupportedArchitectures</key>
<array>
<string>x86_64</string>
</array>
<key>SupportedPlatform</key>
<string>ios</string>
<key>SupportedPlatformVariant</key>
<string>simulator</string>
</dict>
</array>
<key>CFBundlePackageType</key>
<string>XFWK</string>
<key>XCFrameworkFormatVersion</key>
<string>1.0</string>
</dict>
</plist>

View File

@@ -0,0 +1,52 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
@protocol IRTSSEventHandler;
@interface IRTSSStartOption : NSObject
@property (nonatomic, copy) NSString * keyword;
@property (nonatomic, copy) NSArray * keywordList;
@property (nonatomic, copy) NSString * wordLanguage;
@property (nonatomic, copy) NSString * wordType;
@property (nonatomic, assign) BOOL isCloseConnHitted;
@property (nonatomic, assign) BOOL enableIsHit;
@property (nonatomic, assign) BOOL enableIsReturnText;
@property (nonatomic, copy) NSDictionary * extra;
@end
/*
* 接口要确保在UI线程中调用
*/
@protocol IRTSS <NSObject>
/// 初始化SDK
/// @param organization <#organization description#>
/// @param accessKey <#accessKey description#>
/// @param appId <#appId description#>
/// @param wsURL <#wsURL description#>
/// @param httpUrl <#httpUrl description#>
- (BOOL)init:(NSString *)organization accessKey:(NSString *)accessKey appId:(NSString *)appId wsURL:(NSString*)wsURL httpUrl:(NSString*)httpUrl language:(NSString *)language;
- (BOOL)start:(IRTSSStartOption *)option listener:(id<IRTSSEventHandler>)listener;
/// 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
/// @param data PCM数据
- (void)push:(NSData *)data;
/// 断开连接如果想继续工作必须重新调用start()新建连接
- (void)stop;
/// 销毁SDK
- (void)destroy;
@end

View File

@@ -0,0 +1,15 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
#import "RTSSResult.h"
@protocol IRTSSEventHandler <NSObject>
-(void)onRtssSuccess:(RTSSResult *)result repeated:(BOOL) repeated;
-(void)onRtssError:(NSInteger)errCode errMsg:(NSString *)errMsg;
@end

View File

@@ -0,0 +1,10 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ISudAPPD : NSObject
+ (void)e:(int)v;
+ (void)d;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ISudASR <NSObject>
/**
* 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
* data一定都要是有效数据否则精确性有影响
*/
- (void) pushAudio:(NSData *)data;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,55 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSMStateHandle;
@protocol ISudFSMMG <NSObject>
/// 游戏日志
/// 最低版本v1.1.30.xx
-(void) onGameLog:(NSString*)dataJson;
/// 游戏开始
/// 最低版本v1.1.30.xx
-(void) onGameStarted;
/// 游戏销毁
/// 最低版本v1.1.30.xx
-(void) onGameDestroyed;
/// 短期令牌code过期
/// APP接入方需要调用handle.success或handle.fail
/// @param dataJson {"code":"value"}
-(void) onExpireCode:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson;
/// 获取游戏View信息
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param dataJson {}
-(void) onGetGameViewInfo:(id<ISudFSMStateHandle>) handle dataJson:(NSString*)dataJson;
/// 获取游戏Config
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param dataJson dataJson
/// 最低版本v1.1.30.xx
-(void) onGetGameCfg:(id<ISudFSMStateHandle>) handle dataJson:(NSString*)dataJson;
/// 游戏状态变化
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param state state
/// @param dataJson dataJson
-(void) onGameStateChange:(id<ISudFSMStateHandle>) handle state:(NSString*) state dataJson:(NSString*) dataJson;
/// 游戏玩家状态变化
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param userId userId
/// @param state state
/// @param dataJson dataJson
-(void) onPlayerStateChange:(nullable id<ISudFSMStateHandle>) handle userId:(NSString*) userId state:(NSString*) state dataJson:(NSString*) dataJson;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,11 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// APP接入方需要调用handle.success或handle.fail
@protocol ISudFSMStateHandle <NSObject>
-(void) success:(NSString*) dataJson;
-(void) failure:(NSString*) dataJson;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,55 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ISudListenerNotifyStateChange.h"
#import "ISudListenerASR.h"
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSMMG;
@protocol ISudASR;
@protocol ISudFSTAPP <NSObject>
/// 获取游戏View
/// @return UIView
- (UIView *)getGameView;
/// 销毁游戏
/// @return boolean
- (bool)destroyMG;
/// 更新短期令牌code
/// @param code 短期令牌code
/// @param listener 回调只表示APP状态通知到了小游戏不表示小游戏执行了别的逻辑代码比如游戏业务逻辑网络请求一般传null。
- (void)updateCode:(NSString *) code listener:(ISudListenerNotifyStateChange) listener;
/// 获取游戏状态
/// @param state state
/// @return json
- (NSString*)getGameState:(NSString*) state;
/// 获取玩家状态
/// @param userId userId
/// @param state state
/// @return json
- (NSString*)getPlayerState:(NSString*) userId state:(NSString*) state;
/// APP状态通知给小游戏
/// @param state state
/// @param dataJson example: {"key": "value"}
/// @param listener 回调只表示APP状态通知到了小游戏不表示小游戏执行了别的逻辑代码比如游戏业务逻辑网络请求一般传null。
- (void)notifyStateChange:(const NSString *)state dataJson:(NSString *)dataJson listener:(ISudListenerNotifyStateChange) listener;
/// 继续游戏
- (void) playMG;
/// 暂停游戏
- (void) pauseMG;
/// 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
/// @param data pcm数据
- (void)pushAudio:(NSData *)data;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerASRResult)(NSString * asrResult, NSArray * asrResults);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class GameInfo;
typedef void (^ISudListenerGetFQSInfo)(int retCode, const NSString* retMsg, NSString* sdkTokenUrl);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class GameInfo;
typedef void (^ISudListenerGetMGInfo)(int retCode, const NSString* retMsg, GameInfo* gameInfo);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerGetMGList)(int retCode, const NSString* retMsg, const NSString* dataJson);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerInitSDK)(int retCode, const NSString* retMsg);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerNotifyStateChange)(int retCode, const NSString* retMsg, const NSString* dataJson);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerUninitSDK)(int retCode, const NSString* retMsg);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,41 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Priority constant for the println method; use Log.v.
*/
#define LogVERBOSE 2
/**
* Priority constant for the println method; use Log.d.
*/
#define LogDEBUG 3
/**
* Priority constant for the println method; use Log.i.
*/
#define LogINFO 4
/**
* Priority constant for the println method; use Log.w.
*/
#define LogWARN 5
/**
* Priority constant for the println method; use Log.e.
*/
#define LogERROR 6
/**
* Priority constant for the println method.
*/
#define LogASSERT 7
@protocol ISudLogger <NSObject>
- (void) setLogLevel:(int) level;
- (void) log:(int) level tag:(NSString*) tag msg:(NSString*) msg;
- (void) log:(int) level tag:(NSString*) tag msg:(NSString*) msg error:(NSError *) error;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,22 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
@interface RTSSResult : NSObject
@property (nonatomic, assign) BOOL isHit;
@property (nonatomic, copy) NSString * keyword;
@property (nonatomic, copy) NSString * text;
@property (nonatomic, copy) NSString * wordType;
@property (nonatomic, copy) NSArray * keyWordList;
@property (nonatomic, copy) NSArray * numberList;
@end

View File

@@ -0,0 +1,19 @@
//
// SmRtAsr.h
// SmRtAsr
//
// Created by wangyankun on 2021/10/27.
//
#import <Foundation/Foundation.h>
////! Project version number for SmRtAsr.
//FOUNDATION_EXPORT double SmRtAsrVersionNumber;
//
////! Project version string for SmRtAsr.
//FOUNDATION_EXPORT const unsigned char SmRtAsrVersionString[];
//
//// In this header, you should import all the public headers of your framework using statements like #import <SmRtAsr/PublicHeader.h>
//
#import "SmRtAsrClient.h"

View File

@@ -0,0 +1,126 @@
//
// SmRtAsrClient.h
// SmRtAsr
//
// Created by wangyankun on 2021/10/28.
//
#import <Foundation/Foundation.h>
/**
uninit idle sending
create 去到idle 不允许,回调错误 不允许,回调错误
startSession 不允许 去到sending 去到sending
postAudio 不允许 去到idle sending
stopSession 不允许 去到idle 去到idle
destroy unint unint unint
*/
//SmRtAsrClient的配置文件
@interface SmRtAsrOption : NSObject
@property NSString *organization;
@property NSString *appId;
@property NSString *accessKey;
@property NSString *wsUrl;
@property NSString *httpSessionUrl;
@end
//定义response
@interface SmAsrResponse : NSObject
@property int code;
@property NSString * requestId;
@property NSString * tokenId;
@property NSString * sessionId;
@property int segId;
@property NSInteger type;
@property long startTime;
@property long endTime;
@property NSString * text;
@property NSString * eventId;
@property long wsTime;
@property long weTime;
@property long sessionStartTime;
@property long sessionEndTime;
@property long segStartTime;
@property long segEndTime;
@property NSArray<NSDictionary*> *matchedResults;
@property int requestSegId;
@property int responseSegId;
@property NSDictionary* raw;
//[
//{"hitItemContent":"","positions":[[2,9],[10,13]]},
//{"hitItemContent":"","positions":[[2,9],[10,13]]}
//]
@property NSArray<NSDictionary*> *numbers;
@property NSString *message;
@property NSDictionary *detail;//{"errorCode":1}
-(BOOL)isHit;
@end
//定义delegate
@protocol SmRtDelegate <NSObject>
@required -(void) onRtReceived:(NSString*) sessionId
requestId:(NSString*)requestId
response:(SmAsrResponse *)response;
@required -(void) onRtError:(NSString*) sessionId
requestId:(NSString*)requestId
errorCode:(NSInteger)errorCode
message:(NSString*)message;
@end
//定义session的config配置
@interface SmRtSessionConfig : NSObject
@property NSArray<NSString*> *keyWords;
@property BOOL returnAll;
@property NSString *voiceType;
@property NSString *voiceEncode;
@property NSString *tokenId;
@property NSString *eventId;
@property int voiceSample;
@property BOOL enableMatch;
@property BOOL returnText;
@property NSString *language;
@property NSString *matchMode;
@property BOOL returnNumbers;
@property NSDictionary *extra;
@property NSString* authToken;
@property __weak id delegate;
-(NSDictionary*) toJson;
@end
@interface SmRtAsrClient : NSObject
- (instancetype)init NS_UNAVAILABLE;
+(instancetype)shareInstance;
-(instancetype)initWithOption:(SmRtAsrOption *)option;
-(void) startSession:(SmRtSessionConfig*) config;
-(BOOL) postAudio:(NSData *)audioClip;
-(void) stopSession;
-(void) destroy;
-(NSString*) getSDKVersion;
-(SmRtAsrOption *) getAsrOption;
@end

View File

@@ -0,0 +1,35 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "ISudListenerGetFQSInfo.h"
#import "ISudListenerGetMGInfo.h"
#import "ISudAPPD.h"
#import "ISudASR.h"
#import "ISudFSMMG.h"
#import "ISudFSMStateHandle.h"
#import "ISudFSTAPP.h"
#import "ISudListenerASR.h"
#import "ISudListenerGetMGList.h"
#import "ISudListenerInitSDK.h"
#import "ISudListenerNotifyStateChange.h"
#import "ISudListenerUninitSDK.h"
#import "ISudLogger.h"
#import "SudMGP.h"
#import "IRTSS.h"
#import "IRTSSEventHandler.h"
#import "RTSSResult.h"
#import "SmRtAsr.h"
#import "SmRtAsrClient.h"
FOUNDATION_EXPORT double SudMGPVersionNumber;
FOUNDATION_EXPORT const unsigned char SudMGPVersionString[];

View File

@@ -0,0 +1,84 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ISudListenerInitSDK.h"
#import "ISudListenerGetMGList.h"
#import "ISudListenerUninitSDK.h"
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSTAPP;
@protocol ISudFSMMG;
@interface SudMGP : NSObject
/**
* 获取SDK版本
* @return 示例:"1.1.35.286"
*/
+ (NSString*_Nonnull)getVersion;
/**
* 初始化SDK
* @param context Context
* @param appId 小游戏平台生成
* @param appKey 小游戏平台生成
* @param isTestEnv true:测试环境 false:生产环境
* @param listener ISudListenerInitSDK
*/
+ (void)initSDK:(NSString*_Nonnull)appId
appKey:(NSString*_Nonnull)appKey
isTestEnv:(BOOL)isTestEnv
listener:(ISudListenerInitSDK _Nullable )listener;
/**
* 反初始化SDK
* @param listener ISudListenerUninitSDK
*/
+ (void)uninitSDK:(ISudListenerUninitSDK _Nullable )listener;
/**
* 获取游戏列表
* @param listener ISudListenerGetMGList
*/
+ (void)getMGList:(ISudListenerGetMGList _Nullable )listener;
/**
* 加载游戏
* @param userId 用户ID业务系统保证每个用户拥有唯一ID
* @param roomId 房间ID业务系统保证唯一性进入同一房间内
* @param code 短期令牌Code
* @param mgId 小游戏ID测试环境和生成环境小游戏ID是一致的
* @param language 游戏语言 现支持简体zh-CN 繁体zh-TW 英语en-US 马来语ms-MY
* @param fsmMG ISudFSMMG
* @param rootView 用于显示游戏的根视图
* @return ISudFSTAPP
*/
+ (id<ISudFSTAPP>_Nonnull)loadMG:(NSString*_Nonnull)userId
roomId:(NSString*_Nonnull)roomId
code:(NSString*_Nonnull)code
mgId:(int64_t)mgId
language:(NSString*_Nonnull)language
fsmMG:(id<ISudFSMMG>_Nonnull)fsmMG
rootView:(UIView*_Nonnull)rootView;
/**
* 销毁游戏
* @param fstApp 加载游戏返回的对象ISudFSTAPP
* @return boolean
*/
+ (bool)destroyMG:(id<ISudFSTAPP>_Nonnull) fstAPP;
/**
* 设置日志等级
* @param logLevel 输出log的等级,LogVERBOSE,LogDEBUG,LogINFO 见ISudLogger.h
*/
+ (void)setLogLevel:(int)logLevel;
/// 设置是否由SDK设置AudioSession
/// @param autoSet 是否由SDK自动设置
+ (void)autoSetAudioSession:(BOOL)autoSet;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
framework module SudMGP {
umbrella header "SudMGP-umbrella.h"
export *
module * { export * }
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

View File

@@ -0,0 +1,52 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
@protocol IRTSSEventHandler;
@interface IRTSSStartOption : NSObject
@property (nonatomic, copy) NSString * keyword;
@property (nonatomic, copy) NSArray * keywordList;
@property (nonatomic, copy) NSString * wordLanguage;
@property (nonatomic, copy) NSString * wordType;
@property (nonatomic, assign) BOOL isCloseConnHitted;
@property (nonatomic, assign) BOOL enableIsHit;
@property (nonatomic, assign) BOOL enableIsReturnText;
@property (nonatomic, copy) NSDictionary * extra;
@end
/*
* 接口要确保在UI线程中调用
*/
@protocol IRTSS <NSObject>
/// 初始化SDK
/// @param organization <#organization description#>
/// @param accessKey <#accessKey description#>
/// @param appId <#appId description#>
/// @param wsURL <#wsURL description#>
/// @param httpUrl <#httpUrl description#>
- (BOOL)init:(NSString *)organization accessKey:(NSString *)accessKey appId:(NSString *)appId wsURL:(NSString*)wsURL httpUrl:(NSString*)httpUrl language:(NSString *)language;
- (BOOL)start:(IRTSSStartOption *)option listener:(id<IRTSSEventHandler>)listener;
/// 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
/// @param data PCM数据
- (void)push:(NSData *)data;
/// 断开连接如果想继续工作必须重新调用start()新建连接
- (void)stop;
/// 销毁SDK
- (void)destroy;
@end

View File

@@ -0,0 +1,15 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
#import "RTSSResult.h"
@protocol IRTSSEventHandler <NSObject>
-(void)onRtssSuccess:(RTSSResult *)result repeated:(BOOL) repeated;
-(void)onRtssError:(NSInteger)errCode errMsg:(NSString *)errMsg;
@end

View File

@@ -0,0 +1,10 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ISudAPPD : NSObject
+ (void)e:(int)v;
+ (void)d;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ISudASR <NSObject>
/**
* 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
* data一定都要是有效数据否则精确性有影响
*/
- (void) pushAudio:(NSData *)data;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,55 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSMStateHandle;
@protocol ISudFSMMG <NSObject>
/// 游戏日志
/// 最低版本v1.1.30.xx
-(void) onGameLog:(NSString*)dataJson;
/// 游戏开始
/// 最低版本v1.1.30.xx
-(void) onGameStarted;
/// 游戏销毁
/// 最低版本v1.1.30.xx
-(void) onGameDestroyed;
/// 短期令牌code过期
/// APP接入方需要调用handle.success或handle.fail
/// @param dataJson {"code":"value"}
-(void) onExpireCode:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson;
/// 获取游戏View信息
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param dataJson {}
-(void) onGetGameViewInfo:(id<ISudFSMStateHandle>) handle dataJson:(NSString*)dataJson;
/// 获取游戏Config
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param dataJson dataJson
/// 最低版本v1.1.30.xx
-(void) onGetGameCfg:(id<ISudFSMStateHandle>) handle dataJson:(NSString*)dataJson;
/// 游戏状态变化
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param state state
/// @param dataJson dataJson
-(void) onGameStateChange:(id<ISudFSMStateHandle>) handle state:(NSString*) state dataJson:(NSString*) dataJson;
/// 游戏玩家状态变化
/// APP接入方需要调用handle.success或handle.fail
/// @param handle ISudFSMStateHandle
/// @param userId userId
/// @param state state
/// @param dataJson dataJson
-(void) onPlayerStateChange:(nullable id<ISudFSMStateHandle>) handle userId:(NSString*) userId state:(NSString*) state dataJson:(NSString*) dataJson;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,11 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// APP接入方需要调用handle.success或handle.fail
@protocol ISudFSMStateHandle <NSObject>
-(void) success:(NSString*) dataJson;
-(void) failure:(NSString*) dataJson;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,55 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ISudListenerNotifyStateChange.h"
#import "ISudListenerASR.h"
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSMMG;
@protocol ISudASR;
@protocol ISudFSTAPP <NSObject>
/// 获取游戏View
/// @return UIView
- (UIView *)getGameView;
/// 销毁游戏
/// @return boolean
- (bool)destroyMG;
/// 更新短期令牌code
/// @param code 短期令牌code
/// @param listener 回调只表示APP状态通知到了小游戏不表示小游戏执行了别的逻辑代码比如游戏业务逻辑网络请求一般传null。
- (void)updateCode:(NSString *) code listener:(ISudListenerNotifyStateChange) listener;
/// 获取游戏状态
/// @param state state
/// @return json
- (NSString*)getGameState:(NSString*) state;
/// 获取玩家状态
/// @param userId userId
/// @param state state
/// @return json
- (NSString*)getPlayerState:(NSString*) userId state:(NSString*) state;
/// APP状态通知给小游戏
/// @param state state
/// @param dataJson example: {"key": "value"}
/// @param listener 回调只表示APP状态通知到了小游戏不表示小游戏执行了别的逻辑代码比如游戏业务逻辑网络请求一般传null。
- (void)notifyStateChange:(const NSString *)state dataJson:(NSString *)dataJson listener:(ISudListenerNotifyStateChange) listener;
/// 继续游戏
- (void) playMG;
/// 暂停游戏
- (void) pauseMG;
/// 传入的音频数据必须是PCM格式采样率16000 采样位数16 声道数: MONO
/// @param data pcm数据
- (void)pushAudio:(NSData *)data;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerASRResult)(NSString * asrResult, NSArray * asrResults);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class GameInfo;
typedef void (^ISudListenerGetFQSInfo)(int retCode, const NSString* retMsg, NSString* sdkTokenUrl);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,9 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class GameInfo;
typedef void (^ISudListenerGetMGInfo)(int retCode, const NSString* retMsg, GameInfo* gameInfo);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerGetMGList)(int retCode, const NSString* retMsg, const NSString* dataJson);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerInitSDK)(int retCode, const NSString* retMsg);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerNotifyStateChange)(int retCode, const NSString* retMsg, const NSString* dataJson);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void (^ISudListenerUninitSDK)(int retCode, const NSString* retMsg);
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,41 @@
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
* Priority constant for the println method; use Log.v.
*/
#define LogVERBOSE 2
/**
* Priority constant for the println method; use Log.d.
*/
#define LogDEBUG 3
/**
* Priority constant for the println method; use Log.i.
*/
#define LogINFO 4
/**
* Priority constant for the println method; use Log.w.
*/
#define LogWARN 5
/**
* Priority constant for the println method; use Log.e.
*/
#define LogERROR 6
/**
* Priority constant for the println method.
*/
#define LogASSERT 7
@protocol ISudLogger <NSObject>
- (void) setLogLevel:(int) level;
- (void) log:(int) level tag:(NSString*) tag msg:(NSString*) msg;
- (void) log:(int) level tag:(NSString*) tag msg:(NSString*) msg error:(NSError *) error;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,22 @@
//
// Created by Herbert on 2021/10/21.
//
#import <Foundation/Foundation.h>
@interface RTSSResult : NSObject
@property (nonatomic, assign) BOOL isHit;
@property (nonatomic, copy) NSString * keyword;
@property (nonatomic, copy) NSString * text;
@property (nonatomic, copy) NSString * wordType;
@property (nonatomic, copy) NSArray * keyWordList;
@property (nonatomic, copy) NSArray * numberList;
@end

View File

@@ -0,0 +1,19 @@
//
// SmRtAsr.h
// SmRtAsr
//
// Created by wangyankun on 2021/10/27.
//
#import <Foundation/Foundation.h>
////! Project version number for SmRtAsr.
//FOUNDATION_EXPORT double SmRtAsrVersionNumber;
//
////! Project version string for SmRtAsr.
//FOUNDATION_EXPORT const unsigned char SmRtAsrVersionString[];
//
//// In this header, you should import all the public headers of your framework using statements like #import <SmRtAsr/PublicHeader.h>
//
#import "SmRtAsrClient.h"

View File

@@ -0,0 +1,126 @@
//
// SmRtAsrClient.h
// SmRtAsr
//
// Created by wangyankun on 2021/10/28.
//
#import <Foundation/Foundation.h>
/**
uninit idle sending
create 去到idle 不允许,回调错误 不允许,回调错误
startSession 不允许 去到sending 去到sending
postAudio 不允许 去到idle sending
stopSession 不允许 去到idle 去到idle
destroy unint unint unint
*/
//SmRtAsrClient的配置文件
@interface SmRtAsrOption : NSObject
@property NSString *organization;
@property NSString *appId;
@property NSString *accessKey;
@property NSString *wsUrl;
@property NSString *httpSessionUrl;
@end
//定义response
@interface SmAsrResponse : NSObject
@property int code;
@property NSString * requestId;
@property NSString * tokenId;
@property NSString * sessionId;
@property int segId;
@property NSInteger type;
@property long startTime;
@property long endTime;
@property NSString * text;
@property NSString * eventId;
@property long wsTime;
@property long weTime;
@property long sessionStartTime;
@property long sessionEndTime;
@property long segStartTime;
@property long segEndTime;
@property NSArray<NSDictionary*> *matchedResults;
@property int requestSegId;
@property int responseSegId;
@property NSDictionary* raw;
//[
//{"hitItemContent":"","positions":[[2,9],[10,13]]},
//{"hitItemContent":"","positions":[[2,9],[10,13]]}
//]
@property NSArray<NSDictionary*> *numbers;
@property NSString *message;
@property NSDictionary *detail;//{"errorCode":1}
-(BOOL)isHit;
@end
//定义delegate
@protocol SmRtDelegate <NSObject>
@required -(void) onRtReceived:(NSString*) sessionId
requestId:(NSString*)requestId
response:(SmAsrResponse *)response;
@required -(void) onRtError:(NSString*) sessionId
requestId:(NSString*)requestId
errorCode:(NSInteger)errorCode
message:(NSString*)message;
@end
//定义session的config配置
@interface SmRtSessionConfig : NSObject
@property NSArray<NSString*> *keyWords;
@property BOOL returnAll;
@property NSString *voiceType;
@property NSString *voiceEncode;
@property NSString *tokenId;
@property NSString *eventId;
@property int voiceSample;
@property BOOL enableMatch;
@property BOOL returnText;
@property NSString *language;
@property NSString *matchMode;
@property BOOL returnNumbers;
@property NSDictionary *extra;
@property NSString* authToken;
@property __weak id delegate;
-(NSDictionary*) toJson;
@end
@interface SmRtAsrClient : NSObject
- (instancetype)init NS_UNAVAILABLE;
+(instancetype)shareInstance;
-(instancetype)initWithOption:(SmRtAsrOption *)option;
-(void) startSession:(SmRtSessionConfig*) config;
-(BOOL) postAudio:(NSData *)audioClip;
-(void) stopSession;
-(void) destroy;
-(NSString*) getSDKVersion;
-(SmRtAsrOption *) getAsrOption;
@end

View File

@@ -0,0 +1,35 @@
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "ISudListenerGetFQSInfo.h"
#import "ISudListenerGetMGInfo.h"
#import "ISudAPPD.h"
#import "ISudASR.h"
#import "ISudFSMMG.h"
#import "ISudFSMStateHandle.h"
#import "ISudFSTAPP.h"
#import "ISudListenerASR.h"
#import "ISudListenerGetMGList.h"
#import "ISudListenerInitSDK.h"
#import "ISudListenerNotifyStateChange.h"
#import "ISudListenerUninitSDK.h"
#import "ISudLogger.h"
#import "SudMGP.h"
#import "IRTSS.h"
#import "IRTSSEventHandler.h"
#import "RTSSResult.h"
#import "SmRtAsr.h"
#import "SmRtAsrClient.h"
FOUNDATION_EXPORT double SudMGPVersionNumber;
FOUNDATION_EXPORT const unsigned char SudMGPVersionString[];

View File

@@ -0,0 +1,84 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ISudListenerInitSDK.h"
#import "ISudListenerGetMGList.h"
#import "ISudListenerUninitSDK.h"
NS_ASSUME_NONNULL_BEGIN
@protocol ISudFSTAPP;
@protocol ISudFSMMG;
@interface SudMGP : NSObject
/**
* 获取SDK版本
* @return 示例:"1.1.35.286"
*/
+ (NSString*_Nonnull)getVersion;
/**
* 初始化SDK
* @param context Context
* @param appId 小游戏平台生成
* @param appKey 小游戏平台生成
* @param isTestEnv true:测试环境 false:生产环境
* @param listener ISudListenerInitSDK
*/
+ (void)initSDK:(NSString*_Nonnull)appId
appKey:(NSString*_Nonnull)appKey
isTestEnv:(BOOL)isTestEnv
listener:(ISudListenerInitSDK _Nullable )listener;
/**
* 反初始化SDK
* @param listener ISudListenerUninitSDK
*/
+ (void)uninitSDK:(ISudListenerUninitSDK _Nullable )listener;
/**
* 获取游戏列表
* @param listener ISudListenerGetMGList
*/
+ (void)getMGList:(ISudListenerGetMGList _Nullable )listener;
/**
* 加载游戏
* @param userId 用户ID业务系统保证每个用户拥有唯一ID
* @param roomId 房间ID业务系统保证唯一性进入同一房间内
* @param code 短期令牌Code
* @param mgId 小游戏ID测试环境和生成环境小游戏ID是一致的
* @param language 游戏语言 现支持简体zh-CN 繁体zh-TW 英语en-US 马来语ms-MY
* @param fsmMG ISudFSMMG
* @param rootView 用于显示游戏的根视图
* @return ISudFSTAPP
*/
+ (id<ISudFSTAPP>_Nonnull)loadMG:(NSString*_Nonnull)userId
roomId:(NSString*_Nonnull)roomId
code:(NSString*_Nonnull)code
mgId:(int64_t)mgId
language:(NSString*_Nonnull)language
fsmMG:(id<ISudFSMMG>_Nonnull)fsmMG
rootView:(UIView*_Nonnull)rootView;
/**
* 销毁游戏
* @param fstApp 加载游戏返回的对象ISudFSTAPP
* @return boolean
*/
+ (bool)destroyMG:(id<ISudFSTAPP>_Nonnull) fstAPP;
/**
* 设置日志等级
* @param logLevel 输出log的等级,LogVERBOSE,LogDEBUG,LogINFO 见ISudLogger.h
*/
+ (void)setLogLevel:(int)logLevel;
/// 设置是否由SDK设置AudioSession
/// @param autoSet 是否由SDK自动设置
+ (void)autoSetAudioSession:(BOOL)autoSet;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,6 @@
framework module SudMGP {
umbrella header "SudMGP-umbrella.h"
export *
module * { export * }
}

View File

@@ -0,0 +1,582 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>files</key>
<dict>
<key>EgretNativeJSConsoleRes.bundle/Info.plist</key>
<data>
H4tosXOt5Jgj94JFJ+bQ7DZibxA=
</data>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeDirectory</key>
<data>
U4cubFPfT2n+QApbXIm2fGW1B4E=
</data>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeRequirements</key>
<data>
OnX22wWFKRSOFN1+obRynMCeyXM=
</data>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeRequirements-1</key>
<data>
muj1o6L+njvxx86d5ZSUAnpTP84=
</data>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeResources</key>
<data>
/H+GCq1u2MTuKeO3UnDWOp72vHI=
</data>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeSignature</key>
<data>
2jmj7l5rSw0yVb/vlWAYkK/YBwk=
</data>
<key>EgretNativeJSConsoleRes.bundle/index.html</key>
<data>
K/tLkR3L9CMKspWcGjDkJx9cc/Y=
</data>
<key>Headers/IRTSS.h</key>
<data>
f8hSf6ZxCFGUre1kLu6mbYVADi0=
</data>
<key>Headers/IRTSSEventHandler.h</key>
<data>
U1L6bqMpj9HnlnslXq2FOg7WCiQ=
</data>
<key>Headers/ISudAPPD.h</key>
<data>
05P2/6AiTFKVAetmtU1REHdE/W0=
</data>
<key>Headers/ISudASR.h</key>
<data>
z/fF/gwkFzbH6ef/Q1mk8qcyNas=
</data>
<key>Headers/ISudFSMMG.h</key>
<data>
r1CyFyzrDUpN0ti2gOy2g14t1CU=
</data>
<key>Headers/ISudFSMStateHandle.h</key>
<data>
FJ3VAY39qQGfsA5RzchJsPYbjvI=
</data>
<key>Headers/ISudFSTAPP.h</key>
<data>
aItvrTmWvreLyI4LUg68DlFUGfw=
</data>
<key>Headers/ISudListenerASR.h</key>
<data>
e1c1vcvpzWtzpR0M8LXL7DAPJ+M=
</data>
<key>Headers/ISudListenerGetFQSInfo.h</key>
<data>
Z7i09z+EjOM7yuUAv56AhHTf+aM=
</data>
<key>Headers/ISudListenerGetMGInfo.h</key>
<data>
xLG4pxPnoyh3NGW1ERjDuXfSioM=
</data>
<key>Headers/ISudListenerGetMGList.h</key>
<data>
A0jH/DMV6f0s6FRS2BrasrFQzSA=
</data>
<key>Headers/ISudListenerInitSDK.h</key>
<data>
99sNc7pHhNMhxhE/ugBuz/xFC+4=
</data>
<key>Headers/ISudListenerNotifyStateChange.h</key>
<data>
iZ8b1pdDNuD7nHEQYBLp65/hkV4=
</data>
<key>Headers/ISudListenerUninitSDK.h</key>
<data>
ClT1ZLLUSYZr2uY6o7Itdtw1i/Y=
</data>
<key>Headers/ISudLogger.h</key>
<data>
jTVkYtMibuUnks31dwc+LW0ScQE=
</data>
<key>Headers/RTSSResult.h</key>
<data>
80kyv8aQpoAipg6Ia8MkA8kinNQ=
</data>
<key>Headers/SmRtAsr.h</key>
<data>
wvXLscKLU/iJogrD+w0w3hzlhaI=
</data>
<key>Headers/SmRtAsrClient.h</key>
<data>
hshBcpfi1tW5ptVbt6Ox0YI/Wog=
</data>
<key>Headers/SudMGP-umbrella.h</key>
<data>
CiDY/99QZbrSottMgxuMLMyad9M=
</data>
<key>Headers/SudMGP.h</key>
<data>
jnWohTHm9H1gS2UqqpuB7FST1Vc=
</data>
<key>Info.plist</key>
<data>
aBVqUCKzbhq6WmVyMO6W7Pew/nc=
</data>
<key>Modules/module.modulemap</key>
<data>
SqkCCW826QrTr8CHz/pkF0Gg7Uk=
</data>
<key>fsm_mgp_game_loading_progress.png</key>
<data>
dtpNcJpsR3zafFe134BfDkM+F/8=
</data>
<key>fsm_mgp_game_loading_progress_bg.png</key>
<data>
G5Xy+4h7dGMY6FJB5kqFR+sdgmo=
</data>
<key>plugin.zip</key>
<data>
DT5CFEb70VfK0g/AcgYOm5zx5pU=
</data>
<key>sud.png</key>
<data>
vQlHDEdu0+Q1In7/lmqL55xESZU=
</data>
</dict>
<key>files2</key>
<dict>
<key>EgretNativeJSConsoleRes.bundle/Info.plist</key>
<dict>
<key>hash</key>
<data>
H4tosXOt5Jgj94JFJ+bQ7DZibxA=
</data>
<key>hash2</key>
<data>
VrgR5Aq6QlBTDjXaZYYuLo3XXjmQxHt7n+PhvO5wJlc=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeDirectory</key>
<dict>
<key>hash</key>
<data>
U4cubFPfT2n+QApbXIm2fGW1B4E=
</data>
<key>hash2</key>
<data>
wyRBJ57jjdWBHfyHsD3FjEx+hRbs5MA9T0rtCkAdbjw=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeRequirements</key>
<dict>
<key>hash</key>
<data>
OnX22wWFKRSOFN1+obRynMCeyXM=
</data>
<key>hash2</key>
<data>
mHkgkE6rZQ51eIwFSqCwUk5qgL/HGqMt+NI3phdD+YY=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeRequirements-1</key>
<dict>
<key>hash</key>
<data>
muj1o6L+njvxx86d5ZSUAnpTP84=
</data>
<key>hash2</key>
<data>
p4ZGdcZRsD5sItRbkkNihcG9edsDi6w7duzPJwUJ6m0=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeResources</key>
<dict>
<key>hash</key>
<data>
/H+GCq1u2MTuKeO3UnDWOp72vHI=
</data>
<key>hash2</key>
<data>
Xz9YqA4rNI0tJMd5iF39XvmYDFNr/Hiq9RiILIbB/AY=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/_CodeSignature/CodeSignature</key>
<dict>
<key>hash</key>
<data>
2jmj7l5rSw0yVb/vlWAYkK/YBwk=
</data>
<key>hash2</key>
<data>
47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
</data>
</dict>
<key>EgretNativeJSConsoleRes.bundle/index.html</key>
<dict>
<key>hash</key>
<data>
K/tLkR3L9CMKspWcGjDkJx9cc/Y=
</data>
<key>hash2</key>
<data>
gC2TRtg8NJ8h6hVrPmNen2ffzD1Q2jUcUnOpVwi3ue8=
</data>
</dict>
<key>Headers/IRTSS.h</key>
<dict>
<key>hash</key>
<data>
f8hSf6ZxCFGUre1kLu6mbYVADi0=
</data>
<key>hash2</key>
<data>
9IadkR3YfDRV5+/J6zBMbk1mY321NOBoZkoUl73Hg6s=
</data>
</dict>
<key>Headers/IRTSSEventHandler.h</key>
<dict>
<key>hash</key>
<data>
U1L6bqMpj9HnlnslXq2FOg7WCiQ=
</data>
<key>hash2</key>
<data>
0QmC550UmI5oVhvqRAutWrtwRPOF3v2wVvMMcwQm4EE=
</data>
</dict>
<key>Headers/ISudAPPD.h</key>
<dict>
<key>hash</key>
<data>
05P2/6AiTFKVAetmtU1REHdE/W0=
</data>
<key>hash2</key>
<data>
iLOzMPy0oThM1XmDMM6C7c4UWFPM6QlHQZ51R9VFD+Y=
</data>
</dict>
<key>Headers/ISudASR.h</key>
<dict>
<key>hash</key>
<data>
z/fF/gwkFzbH6ef/Q1mk8qcyNas=
</data>
<key>hash2</key>
<data>
qFUhmka9/RnhpNwRpSnwObjSu65Tuhd6QLcQE7wxQU4=
</data>
</dict>
<key>Headers/ISudFSMMG.h</key>
<dict>
<key>hash</key>
<data>
r1CyFyzrDUpN0ti2gOy2g14t1CU=
</data>
<key>hash2</key>
<data>
B9ptVM7f8cBx/ZSr6oHGwR+vMmnJiY1UlCi3lpl3BmU=
</data>
</dict>
<key>Headers/ISudFSMStateHandle.h</key>
<dict>
<key>hash</key>
<data>
FJ3VAY39qQGfsA5RzchJsPYbjvI=
</data>
<key>hash2</key>
<data>
fLMmUKo+hrfIj90HWIRHdfq7v8MI/x0MWQRd9lN1cPE=
</data>
</dict>
<key>Headers/ISudFSTAPP.h</key>
<dict>
<key>hash</key>
<data>
aItvrTmWvreLyI4LUg68DlFUGfw=
</data>
<key>hash2</key>
<data>
en0ZkBmchkyvslIrw3Io4hxHho1yObQIgflmboI/7B4=
</data>
</dict>
<key>Headers/ISudListenerASR.h</key>
<dict>
<key>hash</key>
<data>
e1c1vcvpzWtzpR0M8LXL7DAPJ+M=
</data>
<key>hash2</key>
<data>
ZvLZlglJKF/cbA2rxnPKK/qnPFnSrFjK7mN35COkbT0=
</data>
</dict>
<key>Headers/ISudListenerGetFQSInfo.h</key>
<dict>
<key>hash</key>
<data>
Z7i09z+EjOM7yuUAv56AhHTf+aM=
</data>
<key>hash2</key>
<data>
dgMWSRbsVB/VI4dn14KgIuHyVohZCd6uylOjNtfIHpE=
</data>
</dict>
<key>Headers/ISudListenerGetMGInfo.h</key>
<dict>
<key>hash</key>
<data>
xLG4pxPnoyh3NGW1ERjDuXfSioM=
</data>
<key>hash2</key>
<data>
6XPIfoDCaW2Su+1yD1OKwaNEuOLpqT8Q/6Op7rnBDqg=
</data>
</dict>
<key>Headers/ISudListenerGetMGList.h</key>
<dict>
<key>hash</key>
<data>
A0jH/DMV6f0s6FRS2BrasrFQzSA=
</data>
<key>hash2</key>
<data>
E5N+JajMeuuFCA+bQm/ITWtLis1fB8B6o0SjxC39OVA=
</data>
</dict>
<key>Headers/ISudListenerInitSDK.h</key>
<dict>
<key>hash</key>
<data>
99sNc7pHhNMhxhE/ugBuz/xFC+4=
</data>
<key>hash2</key>
<data>
BpI0OJM3O2t4jgTcMi4o+3Z7mU8f1kFE73Z3VRVbWv4=
</data>
</dict>
<key>Headers/ISudListenerNotifyStateChange.h</key>
<dict>
<key>hash</key>
<data>
iZ8b1pdDNuD7nHEQYBLp65/hkV4=
</data>
<key>hash2</key>
<data>
PWJ/qoGQoZ7q06cdLh64YQbMcdOfkPQ76KGjgzLEbPU=
</data>
</dict>
<key>Headers/ISudListenerUninitSDK.h</key>
<dict>
<key>hash</key>
<data>
ClT1ZLLUSYZr2uY6o7Itdtw1i/Y=
</data>
<key>hash2</key>
<data>
Cuq7ZfNPUJdvjQh33Bn4AiC5gjOAavE6Pu9n6FVoVwM=
</data>
</dict>
<key>Headers/ISudLogger.h</key>
<dict>
<key>hash</key>
<data>
jTVkYtMibuUnks31dwc+LW0ScQE=
</data>
<key>hash2</key>
<data>
iCdKI3ofxZf+tL///BgQljkcPTaFTTY5fU0ptZqIceg=
</data>
</dict>
<key>Headers/RTSSResult.h</key>
<dict>
<key>hash</key>
<data>
80kyv8aQpoAipg6Ia8MkA8kinNQ=
</data>
<key>hash2</key>
<data>
pU2NBhGvfAME1J7lBpqvtZhFVMFZuDiajV/0wiZNDNk=
</data>
</dict>
<key>Headers/SmRtAsr.h</key>
<dict>
<key>hash</key>
<data>
wvXLscKLU/iJogrD+w0w3hzlhaI=
</data>
<key>hash2</key>
<data>
eDzfspvlVv95CQYGVBtfIw/sq8Xp831Y9aewbgc0BpA=
</data>
</dict>
<key>Headers/SmRtAsrClient.h</key>
<dict>
<key>hash</key>
<data>
hshBcpfi1tW5ptVbt6Ox0YI/Wog=
</data>
<key>hash2</key>
<data>
wZqO4WGOpYS+n8/gPU5eimIMFfeYuZCaezw/2uzmh6w=
</data>
</dict>
<key>Headers/SudMGP-umbrella.h</key>
<dict>
<key>hash</key>
<data>
CiDY/99QZbrSottMgxuMLMyad9M=
</data>
<key>hash2</key>
<data>
guPQE5ynbPZNhglA9m1j1LEVSet0AmuMV7bUVmscRa4=
</data>
</dict>
<key>Headers/SudMGP.h</key>
<dict>
<key>hash</key>
<data>
jnWohTHm9H1gS2UqqpuB7FST1Vc=
</data>
<key>hash2</key>
<data>
4bMB1wRViS9RykPPIBLHvJkQ5Y87+6xIrwQjRLTwFaU=
</data>
</dict>
<key>Modules/module.modulemap</key>
<dict>
<key>hash</key>
<data>
SqkCCW826QrTr8CHz/pkF0Gg7Uk=
</data>
<key>hash2</key>
<data>
82DYi24VDJO9ZsI9GZScAIDV9kyxpUfN6/NyRZTI990=
</data>
</dict>
<key>fsm_mgp_game_loading_progress.png</key>
<dict>
<key>hash</key>
<data>
dtpNcJpsR3zafFe134BfDkM+F/8=
</data>
<key>hash2</key>
<data>
PmZ2XWgwRMBpMFC0fewgSN0AQWnYtYfKIc73k87S9No=
</data>
</dict>
<key>fsm_mgp_game_loading_progress_bg.png</key>
<dict>
<key>hash</key>
<data>
G5Xy+4h7dGMY6FJB5kqFR+sdgmo=
</data>
<key>hash2</key>
<data>
kWsbDMHTQ7BUH2wEALcw8lnRExfB0XZ+DgAVGha920M=
</data>
</dict>
<key>plugin.zip</key>
<dict>
<key>hash</key>
<data>
DT5CFEb70VfK0g/AcgYOm5zx5pU=
</data>
<key>hash2</key>
<data>
tLA/Jt5EMBrB1OYfN5RMEx4QjkdrTxizY217oGxA+SU=
</data>
</dict>
<key>sud.png</key>
<dict>
<key>hash</key>
<data>
vQlHDEdu0+Q1In7/lmqL55xESZU=
</data>
<key>hash2</key>
<data>
jGjXGnBah08RrghQiM7wJELGteiQM/iZdJDXE8Bq6C8=
</data>
</dict>
</dict>
<key>rules</key>
<dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^version.plist$</key>
<true/>
</dict>
<key>rules2</key>
<dict>
<key>.*\.dSYM($|/)</key>
<dict>
<key>weight</key>
<real>11</real>
</dict>
<key>^(.*/)?\.DS_Store$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>2000</real>
</dict>
<key>^.*</key>
<true/>
<key>^.*\.lproj/</key>
<dict>
<key>optional</key>
<true/>
<key>weight</key>
<real>1000</real>
</dict>
<key>^.*\.lproj/locversion.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>1100</real>
</dict>
<key>^Base\.lproj/</key>
<dict>
<key>weight</key>
<real>1010</real>
</dict>
<key>^Info\.plist$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^PkgInfo$</key>
<dict>
<key>omit</key>
<true/>
<key>weight</key>
<real>20</real>
</dict>
<key>^embedded\.provisionprofile$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
<key>^version\.plist$</key>
<dict>
<key>weight</key>
<real>20</real>
</dict>
</dict>
</dict>
</plist>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

View File

@@ -123,7 +123,7 @@ typedef NS_ENUM(NSInteger, RoomDatingStateChangeType) {
///是否需要重新选择小游戏,原有小游戏玩法不在最新配置里面是需要重新选择
@property (nonatomic, assign) BOOL isReselect;
///小游戏ID
@property (nonatomic, copy) NSString *mgId;
@property (nonatomic, assign) int64_t mgId;
///小游戏名称
@property (nonatomic, copy) NSString *mgName;
@end

View File

@@ -44,8 +44,7 @@
#import "XPSendGiftView.h"
#import "XPUserCardViewController.h"
#import "XPRoomViewController.h"
#import "XPLittleGameMiniStageView.h"
@interface XPRoomFunctionContainerView ()<XPAcrpssRoomPKPanelViewDelegate, XPLittleGameMiniStageViewDelegate>
@interface XPRoomFunctionContainerView ()<XPAcrpssRoomPKPanelViewDelegate>
///host
@property (nonatomic,weak) id<RoomHostDelegate>delegate;
///
@@ -64,8 +63,6 @@
@property (nonatomic,strong) UIButton *editButton;
///pk
@property (nonatomic,strong) XPAcrpssRoomPKPanelView *acrossPKPanelView;
///
@property (nonatomic,strong) XPLittleGameMiniStageView *littleGameMiniView;
@end
@implementation XPRoomFunctionContainerView
@@ -168,7 +165,6 @@
}];
}
[self updateRoomTopic];
[self showLittleGameMiniView:roomInfo.type];
}
- (void)onRoomEntered {
@@ -206,6 +202,7 @@
} roomUid:roomUid];
}
if (roomInfo.type == RoomType_Anchor) {
[self.contributionButton setTitle:@"主播榜" forState:UIControlStateNormal];
self.anchorGiftValueView.hidden = !roomInfo.showGiftValue;
@@ -224,7 +221,6 @@
}
[self updateRoomTopic];
[self showLittleGameMiniView:roomInfo.type];
}
- (void)onMicroGiftValueUpdate:(NSDictionary *)data {
@@ -383,35 +379,6 @@
}
}
- (void)onMicroQueueUpdate:(NSMutableDictionary<NSString *,MicroQueueModel *> *)queue {
if (self.delegate.getRoomInfo.type == RoomType_MiniGame) {
[self.littleGameMiniView needRefreshPosition:queue];
}
}
#pragma mark -
- (void)showLittleGameMiniView:(RoomType)type {
if (type == RoomType_MiniGame) {
if (!self.littleGameMiniView.superview) {
[self addSubview:self.littleGameMiniView];
[self.littleGameMiniView mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo(0);
make.top.mas_equalTo(kNavigationHeight + 4);
make.height.mas_equalTo(23);
}];
}
} else {
if (self.littleGameMiniView.superview) {
[self.littleGameMiniView removeFromSuperview];
}
}
}
- (void)XPLittleGameMiniStageView:(XPLittleGameMiniStageView *)view didClickFoldButton:(UIButton *)sender {
}
#pragma mark - XPAcrpssRoomPKPanelViewDelegate
- (void)xPAcrpssRoomPKPanelView:(XPAcrpssRoomPKPanelView *)view onlookRoom:(NSString *)roomUid {
[self.delegate exitRoom];
@@ -752,14 +719,4 @@
}
return _acrossPKPanelView;
}
- (XPLittleGameMiniStageView *)littleGameMiniView {
if (!_littleGameMiniView) {
_littleGameMiniView = [[XPLittleGameMiniStageView alloc] init];
_littleGameMiniView.delegate = self;
}
return _littleGameMiniView;
}
@end

View File

@@ -13,6 +13,17 @@ NS_ASSUME_NONNULL_BEGIN
/// 获取小游戏列表
/// @param completion 完成
+ (void)getLittleGameList:(HttpRequestHelperCompletion)completion;
/// 获取小游戏的code
/// @param completion 完成
/// @param uid 用户的uid
+ (void)getSudGameCode:(HttpRequestHelperCompletion)completion uid:(NSString *)uid;
/// 开始游戏检查
/// @param completion 完成
/// @param roomUid 房主的uid
/// @param mgId 游戏的id
+ (void)startGameCheck:(HttpRequestHelperCompletion)completion roomUid:(NSString *)roomUid mgId:(NSString *)mgId;
@end
NS_ASSUME_NONNULL_END

View File

@@ -15,4 +15,21 @@
[self makeRequest:@"miniGame/record/miniGameList" method:HttpRequestHelperMethodPOST completion:completion, __FUNCTION__, nil];
}
/// code
/// @param completion
/// @param uid uid
+ (void)getSudGameCode:(HttpRequestHelperCompletion)completion uid:(NSString *)uid {
[self makeRequest:@"miniGame/getCode" method:HttpRequestHelperMethodPOST completion:completion, __FUNCTION__, uid, nil];
}
///
/// @param completion
/// @param roomUid uid
/// @param mgId id
+ (void)startGameCheck:(HttpRequestHelperCompletion)completion roomUid:(NSString *)roomUid mgId:(NSString *)mgId {
[self makeRequest:@"miniGame/room/startGameCheck" method:HttpRequestHelperMethodPOST completion:completion, __FUNCTION__, roomUid, mgId, nil];
}
@end

View File

@@ -0,0 +1,104 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSData (RW)
#pragma mark - Hash
///=============================================================================
/// @name Hash
///==========
/**
Returns a lowercase NSString for md5 hash.
*/
- (NSString *)md5String;
/**
Returns an NSData for md5 hash.
*/
- (NSData *)md5Data;
/**
Returns a lowercase NSString for sha256 hash.
*/
- (NSString *)sha256String;
/**
Returns a lowercase NSString for sha1 hash.
*/
- (NSString *)sha1String;
/**
Returns an NSData for sha256 hash.
*/
- (NSData *)sha256Data;
#pragma mark - Encode and decode
///=============================================================================
/// @name Encode and decode
///=============================================================================
/**
Returns string decoded in UTF8.
*/
- (nullable NSString *)utf8String;
/**
Returns an NSString for base64 encoded.
*/
- (nullable NSString *)base64EncodedString;
/**
Returns an NSData from base64 encoded string.
@warning This method has been implemented in iOS7.
@param base64EncodedString The encoded string.
*/
+ (nullable NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
/**
Returns an NSDictionary or NSArray for decoded self.
Returns nil if an error occurs.
*/
- (nullable id)jsonValueDecoded;
#pragma mark - Encrypt and Decrypt
///=============================================================================
/// @name Encrypt and Decrypt
///=============================================================================
/**
Returns an encrypted NSData using AES.
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSData encrypted, or nil if an error occurs.
*/
- (nullable NSData *)aesEncryptWithKey:(NSData *)key iv:(nullable NSData *)iv;
/**
Returns an decrypted NSData using AES.
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSData decrypted, or nil if an error occurs.
*/
- (nullable NSData *)aesDecryptWithkey:(NSData *)key iv:(nullable NSData *)iv;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,276 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import "NSData+RW.h"
#include <CommonCrypto/CommonCrypto.h>
@implementation NSData (RW)
- (NSString *)md5String {
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
- (NSData *)md5Data {
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH];
}
- (NSString *)sha256String {
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(self.bytes, (CC_LONG)self.length, result);
NSMutableString *hash = [NSMutableString
stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x", result[i]];
}
return hash;
}
- (NSString *)sha1String {
unsigned char result[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(self.bytes, (CC_LONG)self.length, result);
NSMutableString*hash = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i <CC_SHA1_DIGEST_LENGTH; i++) {
[hash appendFormat:@"%02x",result[i]];
}
return hash;
}
- (NSData *)sha256Data {
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(self.bytes, (CC_LONG)self.length, result);
return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
}
- (NSString *)utf8String {
if (self.length > 0) {
return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
}
return @"";
}
static const char base64EncodingTable[64]
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const short base64DecodingTable[256] = {
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
-2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
- (NSString *)base64EncodedString {
NSUInteger length = self.length;
if (length == 0)
return @"";
NSUInteger out_length = ((length + 2) / 3) * 4;
uint8_t *output = malloc(((out_length + 2) / 3) * 4);
if (output == NULL)
return nil;
const char *input = self.bytes;
NSInteger i, value;
for (i = 0; i < length; i += 3) {
value = 0;
for (NSInteger j = i; j < i + 3; j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = base64EncodingTable[(value >> 18) & 0x3F];
output[index + 1] = base64EncodingTable[(value >> 12) & 0x3F];
output[index + 2] = ((i + 1) < length)
? base64EncodingTable[(value >> 6) & 0x3F]
: '=';
output[index + 3] = ((i + 2) < length)
? base64EncodingTable[(value >> 0) & 0x3F]
: '=';
}
NSString *base64 = [[NSString alloc] initWithBytes:output
length:out_length
encoding:NSASCIIStringEncoding];
free(output);
return base64;
}
+ (NSData *)dataWithBase64EncodedString:(NSString *)base64EncodedString {
NSInteger length = base64EncodedString.length;
const char *string = [base64EncodedString cStringUsingEncoding:NSASCIIStringEncoding];
if (string == NULL)
return nil;
while (length > 0 && string[length - 1] == '=')
length--;
NSInteger outputLength = length * 3 / 4;
NSMutableData *data = [NSMutableData dataWithLength:outputLength];
if (data == nil)
return nil;
if (length == 0)
return data;
uint8_t *output = data.mutableBytes;
NSInteger inputPoint = 0;
NSInteger outputPoint = 0;
while (inputPoint < length) {
char i0 = string[inputPoint++];
char i1 = string[inputPoint++];
char i2 = inputPoint < length ? string[inputPoint++] : 'A';
char i3 = inputPoint < length ? string[inputPoint++] : 'A';
output[outputPoint++] = (base64DecodingTable[i0] << 2)
| (base64DecodingTable[i1] >> 4);
if (outputPoint < outputLength) {
output[outputPoint++] = ((base64DecodingTable[i1] & 0xf) << 4)
| (base64DecodingTable[i2] >> 2);
}
if (outputPoint < outputLength) {
output[outputPoint++] = ((base64DecodingTable[i2] & 0x3) << 6)
| base64DecodingTable[i3];
}
}
return data;
}
- (id)jsonValueDecoded {
NSError *error = nil;
id value = [NSJSONSerialization JSONObjectWithData:self options:kNilOptions error:&error];
if (error) {
NSLog(@"jsonValueDecoded error:%@", error);
}
return value;
}
- (NSData *)aesEncryptWithKey:(NSData *)key iv:(NSData *)iv {
return [self aesOperation:kCCEncrypt key:key iv:iv];
}
- (NSData *)aesDecryptWithkey:(NSData *)key iv:(NSData *)iv {
return [self aesOperation:kCCDecrypt key:key iv:iv];
}
- (nullable NSData *)aesOperation:(CCOperation)operation key:(NSData *)key iv:(nullable NSData *)iv {
if (key.length != 16 && key.length != 24 && key.length != 32) {
return nil;
}
if (iv.length != 16 && iv.length != 0) {
return nil;
}
NSData *result = nil;
size_t bufferSize = self.length + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
if (!buffer) return nil;
size_t encryptedSize = 0;
CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
key.bytes,
key.length,
iv.bytes,
self.bytes,
self.length,
buffer,
bufferSize,
&encryptedSize);
if (cryptStatus == kCCSuccess) {
result = [[NSData alloc]initWithBytes:buffer length:encryptedSize];
free(buffer);
return result;
} else {
free(buffer);
return nil;
}
}
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
//ensure wrapWidth is a multiple of 4
wrapWidth = (wrapWidth / 4) * 4;
const char lookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
long long inputLength = [self length];
const unsigned char *inputBytes = [self bytes];
long long maxOutputLength = (inputLength / 3 + 1) * 4;
maxOutputLength += wrapWidth? (maxOutputLength / wrapWidth) * 2: 0;
unsigned char *outputBytes = (unsigned char *)malloc(maxOutputLength);
long long i;
long long outputLength = 0;
for (i = 0; i < inputLength - 2; i += 3)
{
outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];
outputBytes[outputLength++] = lookup[((inputBytes[i] & 0x03) << 4) | ((inputBytes[i + 1] & 0xF0) >> 4)];
outputBytes[outputLength++] = lookup[((inputBytes[i + 1] & 0x0F) << 2) | ((inputBytes[i + 2] & 0xC0) >> 6)];
outputBytes[outputLength++] = lookup[inputBytes[i + 2] & 0x3F];
//add line break
if (wrapWidth && (outputLength + 2) % (wrapWidth + 2) == 0)
{
outputBytes[outputLength++] = '\r';
outputBytes[outputLength++] = '\n';
}
}
//handle left-over data
if (i == inputLength - 2)
{
// = terminator
outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];
outputBytes[outputLength++] = lookup[((inputBytes[i] & 0x03) << 4) | ((inputBytes[i + 1] & 0xF0) >> 4)];
outputBytes[outputLength++] = lookup[(inputBytes[i + 1] & 0x0F) << 2];
outputBytes[outputLength++] = '=';
}
else if (i == inputLength - 1)
{
// == terminator
outputBytes[outputLength++] = lookup[(inputBytes[i] & 0xFC) >> 2];
outputBytes[outputLength++] = lookup[(inputBytes[i] & 0x03) << 4];
outputBytes[outputLength++] = '=';
outputBytes[outputLength++] = '=';
}
//truncate data to match actual output length
outputBytes = realloc(outputBytes, outputLength);
NSString *result = [[NSString alloc] initWithBytesNoCopy:outputBytes length:outputLength encoding:NSASCIIStringEncoding freeWhenDone:YES];
#if !__has_feature(objc_arc)
[result autorelease];
#endif
return (outputLength >= 4)? result: nil;
}
@end

View File

@@ -0,0 +1,270 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (RW)
#pragma mark - Hash
///=============================================================================
/// @name Hash
///=============================================================================
/**
Returns a lowercase NSString for md5 hash.
*/
- (nullable NSString *)md5String;
/**
Returns a lowercase NSString for sha256 hash.
*/
- (nullable NSString *)sha256String;
/**
Returns a lowercase NSString for sha1 hash.
*/
- (nullable NSString *)sha1String;
/**
对self进行AES加密返回加密后的Base64字符
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSString encrypted, or nil if an error occurs.
*/
- (nullable NSString *)aesEncryptWithKey:(NSString *)key iv:(nullable NSString *)iv;
/**
对self进行AES解密self为Base64字符
@param key A key length of 16, 24 or 32 (128, 192 or 256bits).
@param iv An initialization vector length of 16(128bits).
Pass nil when you don't want to use iv.
@return An NSString encrypted, or nil if an error occurs.
*/
- (nullable NSString *)aesDecryptWithkey:(NSString *)key iv:(nullable NSString *)iv;
#pragma mark - Encode and decode
///=============================================================================
/// @name Encode and decode
///=============================================================================
/**
Returns an NSString for base64 encoded.
*/
- (nullable NSString *)base64EncodedString;
/**
Returns an NSString from base64 encoded string.
@param base64EncodedString string.
*/
+ (nullable NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString;
/**
URL encode a string in utf-8.
@return the encoded string.
*/
- (NSString *)stringByURLEncode;
/**
URL decode a string in utf-8.
@return the decoded string.
*/
- (NSString *)stringByURLDecode;
#pragma mark - Drawing
///=============================================================================
/// @name Drawing
///=============================================================================
/**
* 获取文本标签size
* 截断方式为NSLineBreakByWordWrapping, 对齐方式默认为NSTextAlignmentLeft
* @param font 字体
* @param size 限定范围
*
* @return 返回文本标签实际size
*/
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size;
/**
* 获取文本标签size
* 对齐方式为NSTextAlignmentLeft
* @param font 字体
* @param size 限定范围
* @param lineBreakMode 截断方式
*
* @return 返回文本标签实际size
*/
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size withLineBreakingMode:(NSLineBreakMode)lineBreakMode;
/**
* 获取文本标签size
*
* @param font 字体
* @param size 限定范围
* @param lineBreakingMode 截断方式
* @param textAlignment 文字对齐类型
*
* @return 返回文本标签实际size
*/
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size withLineBreakingMode:(NSLineBreakMode)lineBreakingMode withTextAlignment:(NSTextAlignment)textAlignment;
/**
Returns the width of the string if it were to be rendered with the specified
font on a single line.
@param font The font to use for computing the string width.
@return The width of the resulting string's bounding box. These values may be
rounded up to the nearest whole number.
*/
- (CGFloat)widthForFont:(UIFont *)font;
/**
Returns the height of the string if it were rendered with the specified constraints.
@param font The font to use for computing the string size.
@param width The maximum acceptable width for the string. This value is used
to calculate where line breaks and wrapping would occur.
@return The height of the resulting string's bounding box. These values
may be rounded up to the nearest whole number.
*/
- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width;
#pragma mark - Utilities
///=============================================================================
/// @name Utilities
///=============================================================================
/**
Returns a new UUID NSString
e.g. "D1178E50-2A4D-4F1F-9BD3-F6AAB00E06B1"
*/
+ (NSString *)stringWithUUID;
/**
Trim blank characters (space and newline) in head and tail.
@return the trimmed string.
*/
- (NSString *)stringByTrim;
/**
nil, @"", @" ", @"\n" will Returns NO; otherwise Returns YES.
*/
- (BOOL)isNotBlank;
/**
Returns YES if the target string is contained within the receiver.
@param string A string to test the the receiver.
@discussion Apple has implemented this method in iOS8.
*/
- (BOOL)containsString:(NSString *)string;
/**
Returns YES if the target string is contained within the receiver.
@param string A string to test the the receiver.
@param mask NSStringCompareOptions
*/
- (BOOL)containsString:(NSString *)string options:(NSStringCompareOptions)mask;
/**
Returns YES if the target string is hasPrefix within the receiver.
default NSCaseInsensitiveSearch
@param string A string to test the the receiver.
*/
- (BOOL)hasInsensitivePrefix:(NSString *)string;
/**
Returns YES if the target string is hasPrefix within the receiver.
@param string A string to test the the receiver.
@param mask NSStringCompareOptions
*/
- (BOOL)hasPrefix:(NSString *)string options:(NSStringCompareOptions)mask;
/**
Returns YES if the target CharacterSet is contained within the receiver.
@param set A character set to test the the receiver.
*/
- (BOOL)containsCharacterSet:(NSCharacterSet *)set;
/**
Returns an NSData using UTF-8 encoding.
*/
- (NSData *)dataValue;
/**
Returns NSMakeRange(0, self.length).
*/
- (NSRange)rangeOfAll;
/**
Returns an NSDictionary/NSArray which is decoded from receiver.
Returns nil if an error occurs.
e.g. NSString: @"{"name":"a","count":2}" => NSDictionary: @[@"name":@"a",@"count":@2]
*/
- (id)jsonValueDecoded;
+ (NSString *) jsonStringWithDictionary:(NSDictionary *)dictionary;
//密码需8-16位至少包含字母、数字、符号2种组合
+(BOOL)checkIsHaveNumAndLetter:(NSString*)sting;
/**
中国电信号段为133、149、153、173、177。还有180、181、189、199。
中国联通号段130、131、132、145、155、156、166、171、175、176、185、186、166。
中国移动号段134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、172、178、182、183、184、187、188、198
*/
///判断是否为手机号
- (BOOL)isPhoneNum;
///判断是否包含中文
- (BOOL)isContainsChinese;
///包含特殊字符Special characters
- (BOOL)isContainsSpecialCharacters;
///是否是纯数字
+ (BOOL)isAllNumText:(NSString *)str;
///纯中文字符串
+ (BOOL)isChineseCharacter:(NSString*)source;
///纯英文字符串
+ (BOOL)isEnglishCharacter:(NSString*)source;
///纯特殊字符
+ (BOOL)isAllCharacterString:(NSString *)string;
/// 包含emoji
+ (BOOL)stringContainsEmoji:(NSString *)string;
///去除字符串两端的空格和换行符
- (NSString *)RW_stringByTrimmingCharacters;
/// 汉字转成拼音的方法
+ (NSString *)chineseTransformToPinyin:(NSString *)chinese;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,522 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import "NSString+RW.h"
#import "NSData+RW.h"
@implementation NSString (RW)
-(NSString *)md5String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] md5String];
}
- (NSString *)sha256String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha256String];
}
- (NSString *)sha1String {
return [[self dataUsingEncoding:NSUTF8StringEncoding] sha1String];
}
- (nullable NSString *)aesEncryptWithKey:(NSString *)key iv:(nullable NSString *)iv {
NSData * data = [self dataUsingEncoding:NSUTF8StringEncoding];
data = [data aesEncryptWithKey:[key dataUsingEncoding:NSUTF8StringEncoding]
iv:[iv dataUsingEncoding:NSUTF8StringEncoding]];
//使Base64, 使UTF-8,nil
return [data base64EncodedString];
}
- (nullable NSString *)aesDecryptWithkey:(NSString *)key iv:(nullable NSString *)iv {
NSData * data = [NSData dataWithBase64EncodedString:self];
data = [data aesDecryptWithkey:[key dataUsingEncoding:NSUTF8StringEncoding]
iv:[iv dataUsingEncoding:NSUTF8StringEncoding]];
NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return result;
}
- (NSString *)base64EncodedString {
return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
}
+ (NSString *)stringWithBase64EncodedString:(NSString *)base64EncodedString {
NSData *data = [NSData dataWithBase64EncodedString:base64EncodedString];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (NSString *)stringByURLEncode {
if ([self respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
static NSUInteger const batchSize = 50;
NSUInteger index = 0;
NSMutableString *escaped = @"".mutableCopy;
while (index < self.length) {
NSUInteger length = MIN(self.length - index, batchSize);
NSRange range = NSMakeRange(index, length);
// To avoid breaking up character sequences such as 👴🏻👮🏽
range = [self rangeOfComposedCharacterSequencesForRange:range];
NSString *substring = [self substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded];
index += range.length;
}
return escaped;
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
NSString *encoded = (__bridge_transfer NSString *)
CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
CFSTR("!#$&'()*+,/:;=?@[]"),
cfEncoding);
return encoded;
#pragma clang diagnostic pop
}
}
- (NSString *)stringByURLDecode {
if ([self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
return [self stringByRemovingPercentEncoding];
} else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CFStringEncoding en = CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding);
NSString *decoded = [self stringByReplacingOccurrencesOfString:@"+"
withString:@" "];
decoded = (__bridge_transfer NSString *)
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
NULL,
(__bridge CFStringRef)decoded,
CFSTR(""),
en);
return decoded;
#pragma clang diagnostic pop
}
}
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
{
return [self textSizeWithFont:font constrainedToSize:size withLineBreakingMode:NSLineBreakByWordWrapping];
}
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size withLineBreakingMode:(NSLineBreakMode)lineBreakMode {
return [self textSizeWithFont:font constrainedToSize:size withLineBreakingMode:NSLineBreakByWordWrapping withTextAlignment:NSTextAlignmentLeft];
}
- (CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size withLineBreakingMode:(NSLineBreakMode)lineBreakingMode withTextAlignment:(NSTextAlignment)textAlignment
{
CGSize textSize;
NSMutableParagraphStyle *style = nil;
style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = lineBreakingMode;
style.alignment = textAlignment;
NSMutableDictionary *attributes = [NSMutableDictionary new];
attributes[NSFontAttributeName] = font;
[attributes setValue:style forKey:NSParagraphStyleAttributeName];
if (CGSizeEqualToSize(size, CGSizeZero)) {
textSize = [self sizeWithAttributes:attributes];
}
else {
//NSStringDrawingTruncatesLastVisibleLine NSStringDrawingUsesLineFragmentOrigin NSStringDrawingUsesFontLeading使+=
NSStringDrawingOptions option = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
CGRect rect = [self boundingRectWithSize:size
options:option
attributes:attributes
context:nil];
textSize = rect.size;
}
return textSize;
}
- (CGFloat)widthForFont:(UIFont *)font {
CGSize size = [self textSizeWithFont:font constrainedToSize:CGSizeMake(HUGE, HUGE)];
return size.width;
}
- (CGFloat)heightForFont:(UIFont *)font width:(CGFloat)width {
CGSize size = [self textSizeWithFont:font constrainedToSize:CGSizeMake(width, HUGE)];
return size.height;
}
+ (NSString *)stringWithUUID {
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
return (__bridge_transfer NSString *)string;
}
- (NSString *)stringByTrim {
NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
return [self stringByTrimmingCharactersInSet:set];
}
- (BOOL)isNotBlank {
NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
for (NSInteger i = 0; i < self.length; ++i) {
unichar c = [self characterAtIndex:i];
if (![blank characterIsMember:c]) {
return YES;
}
}
return NO;
}
- (BOOL)containsString:(NSString *)string {
if (string == nil) return NO;
return [self rangeOfString:string].location != NSNotFound;
}
- (BOOL)containsString:(NSString *)string options:(NSStringCompareOptions)mask{
if (string == nil) return NO;
return [self rangeOfString:string options:mask].location != NSNotFound;
}
- (BOOL)hasInsensitivePrefix:(NSString *)string{
if (string == nil) return NO;
NSString *commonStr = [self commonPrefixWithString:string options:NSCaseInsensitiveSearch];
if ([commonStr caseInsensitiveCompare:string] == NSOrderedSame) {
return YES;
}else{
return NO;
}
}
- (BOOL)hasPrefix:(NSString *)string options:(NSStringCompareOptions)mask{
if (string == nil) return NO;
NSString *commonStr = [self commonPrefixWithString:string options:mask];
if ([commonStr caseInsensitiveCompare:string] == NSOrderedSame) {
return YES;
}else{
return NO;
}
}
- (BOOL)containsCharacterSet:(NSCharacterSet *)set {
if (set == nil) return NO;
return [self rangeOfCharacterFromSet:set].location != NSNotFound;
}
- (NSData *)dataValue {
return [self dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSRange)rangeOfAll {
return NSMakeRange(0, self.length);
}
- (id)jsonValueDecoded {
return [[self dataValue] jsonValueDecoded];
}
-(NSString*)coverBodyWithLength:(NSInteger)length
{
NSMutableString* body = [NSMutableString new];
for(int i=0;i<length;i++)
{
[body appendString:@"*"];
}
return body;
}
+(NSString *) jsonStringWithDictionary:(NSDictionary *)dictionary{
NSArray *keys = [dictionary allKeys];
NSMutableString *reString = [NSMutableString string];
[reString appendString:@"{"];
NSMutableArray *keyValues = [NSMutableArray array];
for(int i=0; i<[keys count]; i++) {
NSString *name = [keys objectAtIndex:i];
id valueObj = [dictionary objectForKey:name];
NSString *value = [NSString jsonStringWithObject:valueObj];
if(value) {
[keyValues addObject:[NSString stringWithFormat:@"\"%@\":%@",name,value]];
}
}
[reString appendFormat:@"%@",[keyValues componentsJoinedByString:@","]];
[reString appendString:@"}"];
return reString;
}
+(NSString *)jsonStringWithObject:(id) object{
NSString *value =nil;
if(!object) {
return value;
}
if([object isKindOfClass:[NSString class]]) {
value = [NSString jsonStringWithString:object];
}else if([object isKindOfClass:[NSDictionary class]]){
value = [NSString jsonStringWithDictionary:object];
}else if([object isKindOfClass:[NSArray class]]){
value = [NSString jsonStringWithArray:object];
}
return value;
}
+(NSString *) jsonStringWithString:(NSString *) string{
return[NSString stringWithFormat:@"\"%@\"",
[[string stringByReplacingOccurrencesOfString:@"\n"withString:@"\\n"] stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""]
];
}
+(NSString *) jsonStringWithArray:(NSArray *)array{
NSMutableString *reString = [NSMutableString string];
[reString appendString:@"["];
NSMutableArray *values = [NSMutableArray array];
for(id valueObj in array) {
NSString *value = [NSString jsonStringWithObject:valueObj];
if(value) {
[values addObject:[NSString stringWithFormat:@"%@",value]];
}
}
[reString appendFormat:@"%@",[values componentsJoinedByString:@","]];
[reString appendString:@"]"];
return reString;
}
+ (BOOL)checkIsHaveNumAndLetter:(NSString *)sting{
// !#$%^&*
// ^(?![\d]+$)(?![a-zA-Z]+$)(?![!#$%^&*]+$)[\da-zA-Z!#$%^&*]{8,16}$
//emoji
NSString *regex = @"^(?![\\d]+$)(?![a-zA-Z]+$)(?![^\\da-zA-Z]+$).{8,16}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
return [regextestmobile evaluateWithObject:sting];
// 1(?!.*[·{}\\s-%\\n])
//
// 2(?=.*[a-zA-Z])
//
// 3(?=.*\\d)
//
// 4(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])
//
// 5[^\\u4e00-\\u9fa5] [\\u4e00-\\u9fa5]
//
// 6{6,12} 6~12
//
// NSString *regex = @"^(?!.*[!·(){}【】“”:;,》¥、。‘’——\\s-……%\\n])(?=.*[a-zA-Z])(?=.*\\d)(?=.*[~!@#$%^&*()_+`\\-={}:\";'<>?,.\\/])[^\\u4e00-\\u9fa5]{8,16}$";
//
// //
// NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
//
// //
// NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:sting
// options:NSMatchingReportProgress
// range:NSMakeRange(0, sting.length)];
// //
// NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
//
// //
// NSRegularExpression *specialRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[~!@#$%^&*()_+`\\-={}[]:\";'<>?,.\\/·{}\\s-%\\n]" options:NSRegularExpressionCaseInsensitive error:nil];
//
// //
// NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:sting options:NSMatchingReportProgress range:NSMakeRange(0, sting.length)];
// if (tNumMatchCount == sting.length) { //
// return 1;
//
// } else if (tLetterMatchCount == sting.length) { //
// return 2;
//
// } else if (tNumMatchCount + tLetterMatchCount == sting.length) { //
// return 3;
//
// }else { //
// return 4;
// }
}
- (BOOL)isPhoneNum
{
NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|6[6]|7[0-35-9]|8[0-9]|9[89])\\d{8}$";
NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
return [regextestmobile evaluateWithObject:self];
}
-(BOOL)isContainsChinese{
for(int i=0; i< [self length];i++)
{
int a = [self characterAtIndex:i];
if( a > 0x4E00 && a < 0x9FFF)
{
return YES;
}
}
return NO;
}
- (BOOL)isContainsSpecialCharacters{
NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
NSPredicate* emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
if (![emailTest evaluateWithObject:self]) {
return YES;
}
return NO;
}
//
+ (BOOL)isAllNumText:(NSString *)str{
NSString *regex =@"[0-9]*";
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
if ([pred evaluateWithObject:str]) {
return YES;
}
return NO;
}
+ (BOOL)isChineseCharacter:(NSString*)source {
NSString *regex = @"^[\\u4E00-\\u9FEA]+$";
return ([source rangeOfString:regex options:NSRegularExpressionSearch].length>0);
}
+ (BOOL)isEnglishCharacter:(NSString*)source {
NSString *upperRegex = @"^[\\u0041-\\u005A]+$";
NSString *lowerRegex = @"^[\\u0061-\\u007A]+$";
BOOL isEnglish = (([source rangeOfString:upperRegex options:NSRegularExpressionSearch].length>0) || ([source rangeOfString:lowerRegex options:NSRegularExpressionSearch].length>0));
return isEnglish;
}
+ (BOOL)isAllCharacterString:(NSString *)string
{
NSString *regex = @"[~`!@#$%^&*()_+-=[]|{};':\",./<>?]{,}/";//
//
NSInteger str_length = [string length];
NSInteger allIndex = 0;
for (int i = 0; i<str_length; i++) {
//i
NSString *subStr = [string substringWithRange:NSMakeRange(i, 1)];
if([regex rangeOfString:subStr].location != NSNotFound)
{ //
allIndex++;
}
}
if (str_length == allIndex) {
//
return YES;
}
else
{
//
return NO;
}
}
/// emoji
+ (BOOL)stringContainsEmoji:(NSString *)string{
__block BOOL returnValue = NO;
[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
const unichar hs = [substring characterAtIndex:0];
NSLog(@"hs:%c",hs);
if (0xd800 <= hs && hs <= 0xdbff){
if (substring.length > 1){
const unichar ls = [substring characterAtIndex:1];
const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
if (0x1d000 <= uc && uc <= 0x1f918){
returnValue = YES;
}
}
}else if (substring.length > 1){
const unichar ls = [substring characterAtIndex:1];
if (ls == 0x20e3 || ls == 0xFE0F || ls == 0xd83c){
returnValue = YES;
}
}else{
if (0x2100 <= hs && hs <= 0x27ff){
if (0x278b <= hs && 0x2792 >= hs){
returnValue = NO;
}else{
returnValue = YES;
}
}else if (0x2B05 <= hs && hs <= 0x2b07){
returnValue = YES;
}else if (0x2934 <= hs && hs <= 0x2935){
returnValue = YES;
}else if (0x3297 <= hs && hs <= 0x3299){
returnValue = YES;
}else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50 || hs == 0xd83e){
returnValue = YES;
}
}
}];
return returnValue;
}
- (NSString *)RW_stringByTrimmingCharacters{
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
+ (NSString *)chineseTransformToPinyin:(NSString *)chinese{
CFStringRef hanzi = (__bridge CFStringRef)(chinese);
CFMutableStringRef string = CFStringCreateMutableCopy(NULL, 0, hanzi);
// Boolean CFStringTransform(CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse);
//string
// range NULL
//transform //kCFStringTransformMandarinLatin
//reverse
CFStringTransform(string, NULL, kCFStringTransformMandarinLatin, NO);
//kCFStringTransformStripDiacritics
CFStringTransform(string, NULL, kCFStringTransformStripDiacritics, NO);
NSString * pinyin = (NSString *) CFBridgingRelease(string);
//
pinyin = [pinyin stringByReplacingOccurrencesOfString:@" " withString: @""];
return pinyin;
}
@end

View File

@@ -0,0 +1,93 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
#ifndef RGBA
#define RGBA(r, g, b, a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#endif
#ifndef RGB
#define RGB(r, g, b) RGBA(r, g, b, 1.0f)
#endif
/*
Create UIColor with a hex string.
Example: UIColorHex(0xF0F), UIColorHex(66ccff), UIColorHex(#66CCFF88)
Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
The `#` or "0x" sign is not required.
*/
#ifndef UIColorHex
#define UIColorHex(_hex_) [UIColor RW_colorWithHexString:((__bridge NSString *)CFSTR(#_hex_))]
#endif
/**
* 所有方法前面全部加pawf_, 避免与其他接入的库的category重名导致未知问题.
* 注: colorWithHexString 与接入的某个库有冲突
*/
@interface UIColor (RW)
#pragma mark - Create a UIColor Object
///=============================================================================
/// @name Creating a UIColor Object
///=============================================================================
/**
Creates and returns a color object using the hex RGB color values.
@param rgbValue The rgb value such as 0x66ccff.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)RW_colorWithRGB:(uint32_t)rgbValue;
/**
Creates and returns a color object using the hex RGBA color values.
@param rgbaValue The rgb value such as 0x66ccffff.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)RW_colorWithRGBA:(uint32_t)rgbaValue;
/**
Creates and returns a color object using the specified opacity and RGB hex value.
@param rgbValue The rgb value such as 0x66CCFF.
@param alpha The opacity value of the color object,
specified as a value from 0.0 to 1.0.
@return The color object. The color information represented by this
object is in the device RGB colorspace.
*/
+ (UIColor *)RW_colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha;
/**
Creates and returns a color object from hex string.
@discussion:
Valid format: #RGB #RGBA #RRGGBB #RRGGBBAA 0xRGB ...
The `#` or "0x" sign is not required.
The alpha will be set to 1.0 if there is no alpha component.
It will return nil when an error occurs in parsing.
Example: @"0xF0F", @"66ccff", @"#66CCFF88"
@param hexStr The hex string value for the new color.
@return An UIColor object from string, or nil if an error occurs.
*/
+ (nullable UIColor *)RW_colorWithHexString:(NSString *)hexStr;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,81 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import "UIColor+RW.h"
#import "NSString+RW.h"
@implementation UIColor (RW)
+ (UIColor *)RW_colorWithRGB:(uint32_t)rgbValue {
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
green:((rgbValue & 0xFF00) >> 8) / 255.0f
blue:(rgbValue & 0xFF) / 255.0f
alpha:1];
}
+ (UIColor *)RW_colorWithRGBA:(uint32_t)rgbaValue {
return [UIColor colorWithRed:((rgbaValue & 0xFF000000) >> 24) / 255.0f
green:((rgbaValue & 0xFF0000) >> 16) / 255.0f
blue:((rgbaValue & 0xFF00) >> 8) / 255.0f
alpha:(rgbaValue & 0xFF) / 255.0f];
}
+ (UIColor *)rw_colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha {
return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16) / 255.0f
green:((rgbValue & 0xFF00) >> 8) / 255.0f
blue:(rgbValue & 0xFF) / 255.0f
alpha:alpha];
}
+ (instancetype)RW_colorWithHexString:(NSString *)hexStr {
CGFloat r, g, b, a;
if (hexStrToRGBA(hexStr, &r, &g, &b, &a)) {
return [UIColor colorWithRed:r green:g blue:b alpha:a];
}
return nil;
}
static inline NSUInteger hexStrToInt(NSString *str) {
uint32_t result = 0;
sscanf([str UTF8String], "%X", &result);
return result;
}
static BOOL hexStrToRGBA(NSString *str,
CGFloat *r, CGFloat *g, CGFloat *b, CGFloat *a) {
str = [[str stringByTrim] uppercaseString];
if ([str hasPrefix:@"#"]) {
str = [str substringFromIndex:1];
} else if ([str hasPrefix:@"0X"]) {
str = [str substringFromIndex:2];
}
NSUInteger length = [str length];
// RGB RGBA RRGGBB RRGGBBAA
if (length != 3 && length != 4 && length != 6 && length != 8) {
return NO;
}
//RGB,RGBA,RRGGBB,RRGGBBAA
if (length < 5) {
*r = hexStrToInt([str substringWithRange:NSMakeRange(0, 1)]) / 255.0f;
*g = hexStrToInt([str substringWithRange:NSMakeRange(1, 1)]) / 255.0f;
*b = hexStrToInt([str substringWithRange:NSMakeRange(2, 1)]) / 255.0f;
if (length == 4) *a = hexStrToInt([str substringWithRange:NSMakeRange(3, 1)]) / 255.0f;
else *a = 1;
} else {
*r = hexStrToInt([str substringWithRange:NSMakeRange(0, 2)]) / 255.0f;
*g = hexStrToInt([str substringWithRange:NSMakeRange(2, 2)]) / 255.0f;
*b = hexStrToInt([str substringWithRange:NSMakeRange(4, 2)]) / 255.0f;
if (length == 8) *a = hexStrToInt([str substringWithRange:NSMakeRange(6, 2)]) / 255.0f;
else *a = 1;
}
return YES;
}
@end

View File

@@ -0,0 +1,322 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (RW)
#pragma mark - Create image
///=============================================================================
/// @name Create image
///=============================================================================
/**
Create an animated image with GIF data. After created, you can access
the images via property '.images'. If the data is not animated gif, this
function is same as [UIImage imageWithData:data scale:scale];
@discussion It has a better display performance, but costs more memory
(width * height * frames Bytes). It only suited to display small
gif such as animated emoticon. If you want to display large gif,
see `YYImage`.
@param data GIF data.
@param scale The scale factor
@return A new image created from GIF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithSmallGIFData:(NSData *)data scale:(CGFloat)scale;
/**
Whether the data is animated GIF.
@param data Image data
@return Returns YES only if the data is gif and contains more than one frame,
otherwise returns NO.
*/
+ (BOOL)isAnimatedGIFData:(NSData *)data;
/**
Whether the file in the specified path is GIF.
@param path An absolute file path.
@return Returns YES if the file is gif, otherwise returns NO.
*/
+ (BOOL)isAnimatedGIFFile:(NSString *)path;
/**
Create an image from a PDF file data or path.
@discussion If the PDF has multiple page, is just return's the first page's
content. Image's scale is equal to current screen's scale, size is same as
PDF's origin size.
@param dataOrPath PDF data in `NSData`, or PDF file path in `NSString`.
@return A new image create from PDF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithPDF:(id)dataOrPath;
/**
Create an image from a PDF file data or path.
@discussion If the PDF has multiple page, is just return's the first page's
content. Image's scale is equal to current screen's scale.
@param dataOrPath PDF data in `NSData`, or PDF file path in `NSString`.
@param size The new image's size, PDF's content will be stretched as needed.
@return A new image create from PDF, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithPDF:(id)dataOrPath size:(CGSize)size;
/**
Create a square image from apple emoji.
@discussion It creates a square image from apple emoji, image's scale is equal
to current screen's scale. The original emoji image in `AppleColorEmoji` font
is in size 160*160 px.
@param emoji single emoji, such as @"😄".
@param size image's size.
@return Image from emoji, or nil when an error occurs.
*/
+ (nullable UIImage *)imageWithEmoji:(NSString *)emoji size:(CGFloat)size;
/**
Create and return a 1x1 point size image with the given color.
@param color The color.
*/
+ (nullable UIImage *)imageWithColor:(UIColor *)color;
/**
Create and return a pure color image with the given color and size.
@param color The color.
@param size New image's type.
*/
+ (nullable UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size;
/**
Create and return an image with custom draw code.
@param size The image size.
@param drawBlock The draw block.
@return The new image.
*/
+ (nullable UIImage *)imageWithSize:(CGSize)size drawBlock:(void (^)(CGContextRef context))drawBlock;
#pragma mark - Image Info
///=============================================================================
/// @name Image Info
///=============================================================================
/**
Whether this image has alpha channel.
*/
- (BOOL)hasAlphaChannel;
#pragma mark - Modify Image
///=============================================================================
/// @name Modify Image
///=============================================================================
/**
Returns a new image which is scaled from this image.
The image will be stretched as needed.
@param size The new size to be scaled, values should be positive.
@return The new image with the given size.
*/
- (nullable UIImage *)imageByResizeToSize:(CGSize)size;
/**
Returns a new image which is cropped from this image.
@param rect Image's inner rect.
@return The new image, or nil if an error occurs.
*/
- (nullable UIImage *)imageByCropToRect:(CGRect)rect;
/**
Returns a new image which is edge inset from this image.
@param insets Inset (positive) for each of the edges, values can be negative to 'outset'.
@param color Extend edge's fill color, nil means clear color.
@return The new image, or nil if an error occurs.
*/
- (nullable UIImage *)imageByInsetEdge:(UIEdgeInsets)insets withColor:(nullable UIColor *)color;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to half
the width or height.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius;
/// high speed get RoundCornerRadius Image
/// @param radius radius
- (UIImage *)imageByRoundCornerRadius2:(CGFloat)radius;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to
half the width or height.
@param borderWidth The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
@param borderColor The border stroke color. nil means clear color.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor;
/**
Rounds a new image with a given corner size.
@param radius The radius of each corner oval. Values larger than half the
rectangle's width or height are clamped appropriately to
half the width or height.
@param corners A bitmask value that identifies the corners that you want
rounded. You can use this parameter to round only a subset
of the corners of the rectangle.
@param borderWidth The inset border line width. Values larger than half the rectangle's
width or height are clamped appropriately to half the width
or height.
@param borderColor The border stroke color. nil means clear color.
@param borderLineJoin The border line join.
*/
- (nullable UIImage *)imageByRoundCornerRadius:(CGFloat)radius
corners:(UIRectCorner)corners
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor
borderLineJoin:(CGLineJoin)borderLineJoin;
/**
Returns a new rotated image (relative to the center).
@param radians Rotated radians in counterclockwise.⟲
@param fitSize YES: new image's size is extend to fit all content.
NO: image's size will not change, content may be clipped.
*/
- (nullable UIImage *)imageByRotate:(CGFloat)radians fitSize:(BOOL)fitSize;
/**
Returns a new image rotated counterclockwise by a quarterturn (90°). ⤺
The width and height will be exchanged.
*/
- (nullable UIImage *)imageByRotateLeft90;
/**
Returns a new image rotated clockwise by a quarterturn (90°). ⤼
The width and height will be exchanged.
*/
- (nullable UIImage *)imageByRotateRight90;
/**
Returns a new image rotated 180° . ↻
*/
- (nullable UIImage *)imageByRotate180;
/**
Returns a vertically flipped image. ⥯
*/
- (nullable UIImage *)imageByFlipVertical;
/**
Returns a horizontally flipped image. ⇋
*/
- (nullable UIImage *)imageByFlipHorizontal;
- (UIImage *)imageByGrayscale;
/**
Applies a blur effect to this image. Suitable for blur any content.
*/
- (nullable UIImage *)imageByBlurSoft;
/**
Applies a blur effect to this image. Suitable for blur any content except pure white.
(same as iOS Control Panel)
*/
- (nullable UIImage *)imageByBlurLight;
/**
Applies a blur effect to this image. Suitable for displaying black text.
(same as iOS Navigation Bar White)
*/
- (nullable UIImage *)imageByBlurExtraLight;
/**
Applies a blur effect to this image. Suitable for displaying white text.
(same as iOS Notification Center)
*/
- (nullable UIImage *)imageByBlurDark;
- (UIImage *)imageByBlurWithTint:(UIColor *)tintColor;
- (UIImage *)imageByTintColor:(UIColor *)color;
/**
* 高斯模糊
*/
+ (UIImage *)gaussianFilter:(UIImage *)originImage;
+ (UIImage *)blurryImage:(UIImage *)image withBlurLevel:(CGFloat)blur;
+ (UIImage *)blurryImage1:(UIImage *)image withBlurLevel:(CGFloat)blur;
/**
* 拍照图片旋转
*/
- (UIImage *)normalizedImage;
/// 合成两张图片btmImg在底部topImg在顶部rect是顶部图片相对底部图片的位置
+ (UIImage*)synthesisWithBottomImage:(UIImage *)btmImg topImage:(UIImage*)topImg withTopRect:(CGRect)rect;
/**
* 指定图片大小压缩
*/
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength;
/// 缩小图片到指定尺寸
- (nullable UIImage*)scaleToSize:(CGSize)size;
/// 给图片加上标签
- (UIImage*)addText:(NSString*)text
XPos:(int)xpos
YPos:(int)ypos
bgColor:(UIColor*)bgColor
textColor:(UIColor*)textColor;
@end
NS_ASSUME_NONNULL_END

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class UILabel;
/// 登录接入方服务器url
#warning 登录接入方服务器url修改地址
static NSString* LOGIN_URL = @"https://fat-mgp-hello.sudden.ltd/login";
@interface SudCommon : NSObject
/// 获取用户名
+ (NSString *)getUserName;
/// 字典转JSON
/// @param dic 字典
+ (NSString*)dictionaryToJson:(NSDictionary *)dic;
/// JSON转字典
/// @param turnString JSON
+ (NSDictionary *)turnStringToDictionary:(NSString *)turnString;
/// 登录到接入方服务器
/// @param userid 用户id
/// @param resultCb 回调
+ (void)loginWithUserId:(NSString *)userid resultCallbckBlock:(void(^)(NSString *code, NSError *error))resultCb;
/// 获取带颜色的NSMutableAttributedString
/// @param string string
/// @param color color
+ (NSMutableAttributedString *)getAttributedStringWithString:(NSString *)string color:(NSString*)color;
/// 获取游戏错误表
+ (NSDictionary *)getErrorMap;
/// 获取sdk版本Label
+ (UILabel *)getSDKVersionLabel;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,148 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#import "SudCommon.h"
#import <AFNetworking/AFNetworking.h>
#import "UIColor+RW.h"
#import <SudMGP/SudMGP.h>
#import <CommonCrypto/CommonDigest.h>
@implementation SudCommon
///
+ (NSString *)getUserName {
return [self MD5ForLower8Bate:[self getUUID]];
}
/// uuid
+ (NSString *)getUUID {
return [UIDevice currentDevice].identifierForVendor.UUIDString;;
}
// 8
+(NSString *)MD5ForLower8Bate:(NSString *)str {
NSString *md5Str = [self MD5ForLower32Bate:str];
NSString *string = [md5Str substringWithRange:NSMakeRange(8, 8)];
return string;
}
// 32
+(NSString *)MD5ForLower32Bate:(NSString *)str{
//UTF8
const char* input = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(input, (CC_LONG)strlen(input), result);
NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[digest appendFormat:@"%02x", result[i]];
}
return digest;
}
#pragma mark - =======login=======
///
+ (void)loginWithUserId:(NSString *)userid resultCallbckBlock:(void(^)(NSString *code, NSError *error))resultCb {
AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
/// user_id,uuid
NSDictionary * param = @{@"user_id":[self getUserName]};
[manager POST:LOGIN_URL parameters:param headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary * dic = [responseObject objectForKey:@"data"];
/// codesdk
NSString * code = [dic objectForKey:@"code"];
resultCb(code, nil);
[self invalidateHttpSession:manager];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
resultCb(nil, error);
[self invalidateHttpSession:manager];
}];
}
+ (void)invalidateHttpSession:(AFHTTPSessionManager *)manager{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[manager invalidateSessionCancelingTasks:YES resetSession:NO];
});
}
#pragma mark - json
+ (NSString*)dictionaryToJson:(NSDictionary *)dic {
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
+ (NSDictionary *)turnStringToDictionary:(NSString *)turnString {
NSData *turnData = [turnString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *turnDic = [NSJSONSerialization JSONObjectWithData:turnData options:NSJSONReadingMutableLeaves error:nil];
return turnDic;
}
+ (NSMutableAttributedString *)getAttributedStringWithString:(NSString *)string color:(NSString*)color {
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc]initWithString:string];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor RW_colorWithHexString:color] range:NSMakeRange(0, attributedString.length)];
return attributedString;
}
+ (UILabel *)getSDKVersionLabel {
UILabel * versionLabel = [[UILabel alloc]init];
versionLabel.text = [SudCommon getSDKVersion];
versionLabel.font = [UIFont boldSystemFontOfSize:10];
versionLabel.textColor = [UIColor whiteColor];
versionLabel.textAlignment = NSTextAlignmentRight;
return versionLabel;
}
+ (NSString *)getSDKVersion {
return [NSString stringWithFormat:@"v%@",[SudMGP getVersion]];
}
+ (NSDictionary *)getErrorMap {
return @{
//
@"100000" : @"通用错误",
@"100001" : @"http 缺失code 参数",
@"100002" : @"http 缺失roomID 参数",
@"100003" : @"http 缺失appID 参数",
@"100004" : @"http 缺失openID 参数",
@"100005" : @"code 效验失败或者过期",
@"100006" : @"sdk 请求错误",
@"100007" : @"sdk 参数错误",
@"100008" : @"数据库查询错误",
@"100009" : @"数据库插入错误",
@"100010" : @"数据库修改错误",
//
@"100100" : @"登陆错误",
@"100200" : @"加入房间错误",
@"100201" : @"战斗时房间不能加入",
@"100202" : @"房间人数已满",
@"100203" : @"重复加入",
@"100204" : @"位置上有人",
@"100300" : @"退出错误",
@"100301" : @"不在游戏位",
@"100302" : @"准备或游戏状态不能退出",
@"100400" : @"准备错误",
@"100401" : @"取消准备错误",
@"100500" : @"开始游戏错误",
@"100501" : @"游戏已开始",
@"100502" : @"队长才能开始游戏",
@"100503" : @"有人未准备",
@"100504" : @"开始游戏的人数不足",
@"100600" : @"踢人错误",
@"100601" : @"队长才能踢人",
@"100602" : @"战斗房间不能踢人",
@"100700" : @"换队长错误",
@"100800" : @"逃跑错误",
@"100801" : @"逃跑时游戏已结束",
@"100802" : @"逃跑时玩家已不在游戏中",
@"100900" : @"解散错误",
@"100901" : @"解散时游戏已结束",
@"100902" : @"队长才能解散",
};
}
@end

View File

@@ -0,0 +1,79 @@
/**
* Copyright © Sud.Tech
* https://sud.tech
*/
#ifndef HelloSud_iOS_Define_h
#define HelloSud_iOS_Define_h
#pragma mark - APP-->MG 状态
/// 加入状态
static NSString* APP_COMMON_SELF_IN = @"app_common_self_in";
/// 准备状态
static NSString* APP_COMMON_SELF_READY = @"app_common_self_ready";
/// 游戏状态
static NSString* APP_COMMON_SELF_PLAYING = @"app_common_self_playing";
/// 队长状态
static NSString* APP_COMMON_SELF_CAPTAIN = @"app_common_self_captain";
/// 踢人
static NSString* APP_COMMON_SELF_KICK = @"app_common_self_kick";
/// 结束游戏
static NSString* APP_COMMON_SELF_END = @"app_common_self_end";
/// 房间状态
static NSString* APP_COMMON_SELF_ROOM = @"app_common_self_room";
/// 麦位状态
static NSString* APP_COMMON_SELF_SEAT = @"app_common_self_seat";
/// 麦克风状态
static NSString* APP_COMMON_SELF_MICROPHONE = @"app_common_self_microphone";
/// 文字命中状态
static NSString* APP_COMMON_SELF_TEXT_HIT = @"app_common_self_text_hit";
#pragma mark - 通用状态-游戏
/// 公屏消息
static NSString* MG_COMMON_PUBLIC_MESSAGE = @"mg_common_public_message";
/// 关键词状态
static NSString* MG_COMMON_KEY_WORD_TO_HIT = @"mg_common_key_word_to_hit";
/// 游戏结算状态
static NSString* MG_COMMON_GAME_SETTLE = @"mg_common_game_settle";
/// 加入游戏按钮点击状态
static NSString* MG_COMMON_SELF_CLICK_JOIN_BTN = @"mg_common_self_click_join_btn";
/// 取消加入游戏按钮点击状态
static NSString* MG_COMMON_SELF_CLICK_CANCEL_JOIN_BTN = @"mg_common_self_click_cancel_join_btn";
/// 准备按钮点击状态
static NSString* MG_COMMON_SELF_CLICK_READY_BTN = @"mg_common_self_click_ready_btn";
/// 取消准备按钮点击状态
static NSString* MG_COMMON_SELF_CLICK_CANCEL_READY_BTN = @"mg_common_self_click_cancel_ready_btn";
/// 开始游戏按钮点击状态
static NSString* MG_COMMON_SELF_CLICK_START_BTN = @"mg_common_self_click_start_btn";
#pragma mark - 通用状态-玩家
/// 加入状态
static NSString* MG_COMMON_PLAYER_IN = @"mg_common_player_in";
/// 准备状态
static NSString* MG_COMMON_PLAYER_READY = @"mg_common_player_ready";
/// 队长状态
static NSString* MG_COMMON_PLAYER_CAPTAIN = @"mg_common_player_captain";
/// 游戏状态
static NSString* MG_COMMON_PLAYER_PLAYING = @"mg_common_player_playing";
/// 你画我猜
/// 选词中
static NSString* MG_DG_SELECTING = @"mg_dg_selecting";
/// 作画中
static NSString* MG_DG_PAINTING = @"mg_dg_painting";
/// 错误答案
static NSString* MG_DG_ERRORANSWER = @"mg_dg_erroranswer";
/// 总积分
static NSString* MG_DG_TOTALSCORE = @"mg_dg_totalscore";
/// 本次积分
static NSString* MG_DG_SCORE = @"mg_dg_score";
#define mRoomID @"9009"
#define mLanguage @"zh-CN"
#define MG_ID_BUMPER_CAR 1461227817776713818L//游戏ID:碰碰车
#define MG_ID_FLY_CUTTER 1461228379255603251L//游戏ID:飞刀达人
#define MG_ID_DRAW_GUESS 1461228410184400899L//游戏ID:你画我猜
#define MG_ID_GO_BANG 1461297734886621238L//游戏ID:五子棋
#endif /* AppConfig.h */

View File

@@ -19,6 +19,8 @@ NS_ASSUME_NONNULL_BEGIN
- (void)needRefreshPosition:(NSMutableDictionary *)micQueue;
///代理
@property (nonatomic,weak) id<XPLittleGameMiniStageViewDelegate> delegate;
///隐藏小游戏房大坑位
- (void)hideSudGamePostionView;
@end
NS_ASSUME_NONNULL_END

View File

@@ -43,6 +43,13 @@ UIKIT_EXTERN NSString * const kRoomRoomLittleGameMiniStageNotificationKey;
return self;
}
#pragma mark - Public Method
- (void)hideSudGamePostionView {
self.foldButton.selected = NO;
[self tapAvatarRecognizer];
}
#pragma mark - Private Method
- (void)initSubViews {
self.backgroundColor = UIColorRGBAlpha(0x000000, 0.2);
[self addSubview:self.stackView];

View File

@@ -0,0 +1,17 @@
//
// XPRoomLittleGameContainerView.h
// xplan-ios
//
// Created by 冯硕 on 2022/2/14.
//
#import <UIKit/UIKit.h>
#import "RoomHostDelegate.h"
#import "RoomGuestDelegate.h"
NS_ASSUME_NONNULL_BEGIN
@interface XPRoomLittleGameContainerView : UIView<RoomGuestDelegate>
- (instancetype)initWithDelegate:(id<RoomHostDelegate>)delegate;
@end
NS_ASSUME_NONNULL_END

View File

@@ -0,0 +1,872 @@
//
// XPRoomLittleGameContainerView.m
// xplan-ios
//
// Created by on 2022/2/14.
//
#import "XPRoomLittleGameContainerView.h"
///Third
#import <Masonry/Masonry.h>
#import <SudMGP/SudMGP.h>
#import <NIMSDK/NIMSDK.h>
///Tool
#import "Api+LittleGame.h"
#import "AccountInfoStorage.h"
#import "XCHUDTool.h"
#import "XPConstant.h"
#import "XPMacro.h"
#import "SudCommon.h"
#import "SudGameConfig.h"
///Model
#import "RoomInfoModel.h"
#import "MicroQueueModel.h"
#import "UserInfoModel.h"
#import "MicroExtModel.h"
#import "AttachmentModel.h"
#import "XPKickUserModel.h"
///View
#import "XPLittleGameMiniStageView.h"
///P
#import <SudMGP/ISudFSMMG.h>
#import <SudMGP/ISudFSTAPP.h>
#import <SudMGP/SudMGP.h>
#import <SudMGP/ISudFSMStateHandle.h>
@interface XPRoomLittleGameContainerView ()<RoomGuestDelegate,ISudFSMMG>
///ID
@property (nonatomic, assign) int64_t currentmgId;
///code
@property (nonatomic, copy) NSString *code;
///
@property (nonatomic,weak) id<RoomHostDelegate> hostDelegate;
@property (nonatomic, strong) id<ISudFSTAPP> fsmAPP2MG;
/// DrawSomethingKeyWord
@property (nonatomic, copy) NSString * DrawSomethingKeyWord;
///
@property (nonatomic, assign) BOOL keyWordHiting;
///
@property (nonatomic, assign) LittleGamePlayStatus sudGameStatus;
///
@property (nonatomic, assign) BOOL isPlaying;
///
@property (nonatomic,strong) XPLittleGameMiniStageView *littleGameMiniView;
@end
@implementation XPRoomLittleGameContainerView
- (instancetype)initWithDelegate:(id<RoomHostDelegate>)delegate
{
self = [super init];
if (self) {
self.hostDelegate = delegate;
}
return self;
}
#pragma mark -
- (void)showLittleGameMiniView:(RoomType)type {
if (type == RoomType_MiniGame) {
if (!self.littleGameMiniView.superview) {
[self addSubview:self.littleGameMiniView];
[self.littleGameMiniView mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo(0);
make.top.mas_equalTo(kNavigationHeight + 4);
make.height.mas_equalTo(23);
}];
}
} else {
if (self.littleGameMiniView.superview) {
[self.littleGameMiniView removeFromSuperview];
}
}
}
#pragma mark - Private Method
- (void)updateSudGame {
RoomInfoModel * roomInfo = self.hostDelegate.getRoomInfo;
if (roomInfo.type == RoomType_MiniGame) {
if (self.currentmgId == 0) {//
self.currentmgId = roomInfo.mgId;
if (self.currentmgId != 0) {//
NSLog(@"initLittleGame---%lld", self.currentmgId);
[self initLittleGame];
}
} else {
if (self.currentmgId != roomInfo.mgId) {
//
self.currentmgId = roomInfo.mgId;
NSLog(@"updateLittleGame---%lld", self.currentmgId);
if (self.currentmgId != 0) {
[self destroyMG];
self.isPlaying = NO;
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
[self gameSetUp];
}
}
}
}
[self showLittleGameMiniView:roomInfo.type];
}
- (void)initLittleGame {
[Api getSudGameCode:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code == 200) {
NSString * gameCode = data.data[@"code"];
self.code = gameCode;
[self gameSetUp];
} else {
[XCHUDTool showErrorWithMessage:msg];
}
} uid:[AccountInfoStorage instance].getUid];
}
- (void)gameSetUp {
NSLog(@"小游戏的版本号是:%@", [SudMGP getVersion]);
BOOL isTestEnv = NO;
#ifdef DEBUG
isTestEnv = YES;
#else
isTestEnv = NO;
#endif
[SudMGP initSDK:KeyWithType(KeyType_SudGameAppID) appKey:KeyWithType(KeyType_SudGameAppKey) isTestEnv:isTestEnv listener:^(int retCode, const NSString *retMsg) {
if (retCode == 0) {
if (!self.currentmgId) {
return;
}
NSString * userId = [AccountInfoStorage instance].getUid;
NSString * roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
NSLog(@"用户ID%@房间ID%@, 游戏ID%lld, code:%@", userId, roomId, self.currentmgId, self.code);
self.fsmAPP2MG = [SudMGP loadMG:userId roomId:roomId code:self.code mgId:self.currentmgId language:@"zh-CN" fsmMG:self rootView:self];
} else {
/// ,
NSLog(@"ISudFSMMG:initGameSDKWithAppID:初始化sdk失败 :%@",retMsg);
}
}];
}
//
- (BOOL)isOnMicro:(NSInteger)uid{
NSArray *chatRoomMicSequences = [self.hostDelegate.getMicroQueue allValues] ;
if (chatRoomMicSequences != nil && chatRoomMicSequences.count > 0) {
for (int i = 0; i < chatRoomMicSequences.count; i ++) {
MicroQueueModel *chatRoomMicSequence = chatRoomMicSequences[i];
if (chatRoomMicSequence.userInfo.uid == uid) {
return YES;
}
}
}
return NO;
}
- (NSString *)findFreePosition{
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
if (micQueue != nil && micQueue.allKeys.count > 0) {
NSArray *keys = [micQueue allKeys];
if (keys.count > 0) {
///
NSArray *resultArr = [keys sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2];
}];
for (NSString *key in resultArr) {
UserInfoModel *userInfo = [[micQueue objectForKey:key] userInfo];
if ( !userInfo) {
return key;
}
}
}
}
return nil;
}
//uid
- (NSString *)findThePositionByUid:(NSInteger)uid{
if (uid > 0) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
NSArray *keys = [micQueue allKeys];
if (keys.count > 0) {
for (NSString *key in keys) {
UserInfoModel *userInfo = [[micQueue objectForKey:key] userInfo];
if (userInfo.uid == uid) {
return key;
}
}
}
}
return nil;
}
//
- (void)upMicToJoinGame {
NSString *position = [self findFreePosition];
if (position.length > 0) {
NSString * userId = [AccountInfoStorage instance].getUid;
UserInfoModel * userInfo = self.hostDelegate.getUserInfo;
//uid
if ([self isOnMicro:userId.integerValue]) {
if (position) {
NSString *findOldPosition = [self findThePositionByUid:userInfo.uid];
NIMChatroomQueueRemoveRequest *request = [[NIMChatroomQueueRemoveRequest alloc]init];
request.key = findOldPosition;
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
if (findOldPosition) {
[[NIMSDK sharedSDK].chatroomManager removeChatroomQueueObject:request completion:^(NSError * _Nullable error, NSDictionary<NSString *,NSString *> * _Nullable element) {
if (error == nil) {
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
[self notifySelfInState:YES seatIndex:-1];
}];
}
}];
}
}
}else{
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
[self notifySelfInState:YES seatIndex:-1];
}];
}
}
}
- (void)updateMicInfoWithGameStatus:(LittleGamePlayStatus)status {
NSString * position = [self findThePositionByUid:[AccountInfoStorage instance].getUid.integerValue];
if (position != nil) {
UserInfoModel * userInfo = self.hostDelegate.getUserInfo;
userInfo.gameStatus = status;
NIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc]init];
request.key = position;
request.value = [[self userInfoToQueueExt:userInfo] toJSONString];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.transient = YES;
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request completion:^(NSError * _Nullable error) {
}];
}
}
/**
*
*/
- (NSDictionary *)userInfoToQueueExt:(UserInfoModel *)userInfo {
MicroExtModel * extModel = [[MicroExtModel alloc] init];
extModel.gender = userInfo.gender;
extModel.avatar = userInfo.avatar;
extModel.uid = userInfo.uid;
extModel.nick = userInfo.nick;
extModel.gameStatus = userInfo.gameStatus;
extModel.headWearUrl = userInfo.headwearEffect.length > 0 ? userInfo.headwearEffect : userInfo.headwearPic;
return [extModel model2dictionary];
}
//
- (BOOL)isInSudGame {
BOOL isGamePlaying = NO;
for (int i = -1; i<5; i++) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
MicroQueueModel *micSequence = [micQueue objectForKey:[NSString stringWithFormat:@"%d", i]];
if (micSequence == nil || micSequence.userInfo == nil) {
continue;
}
if (micSequence.userInfo.uid == [AccountInfoStorage instance].getUid.integerValue && micSequence.userInfo.gameStatus == LittleGamePlayStatus_Plying) {
isGamePlaying = YES;
break;
}
}
return isGamePlaying;
}
//
- (LittleGamePlayStatus)getCurrentUserSudGameStatus {
LittleGamePlayStatus gameStatus = LittleGamePlayStatus_NoIn;
for (int i = -1; i<5; i++) {
NSMutableDictionary * micQueue = self.hostDelegate.getMicroQueue;
MicroQueueModel *micSequence = [micQueue objectForKey:[NSString stringWithFormat:@"%d", i]];
if (micSequence == nil || micSequence.userInfo == nil) {
continue;
}
if (micSequence.userInfo.uid == [AccountInfoStorage instance].getUid.integerValue) {
gameStatus = micSequence.userInfo.gameStatus;
break;
}
}
return gameStatus;
}
///
- (void)onDownMic:(NSInteger)uid {
if (uid == [AccountInfoStorage instance].getUid.integerValue) {//
[self notifyIsPlayingState:false];
[self nofityPlayerPlaying:NO];
[self notifySetReady:false];
///
[self notifySelfInState:false seatIndex:-1];
}
}
#pragma mark =======ISudFSMMG Delegate=======
/**
*
*/
-(void)onGameLog:(NSString*)dataJson {
NSLog(@"ISudFSMMG:onGameLog:%@", dataJson);
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
NSString * msg_string = [dic objectForKey:@"msg"];
if (!msg_string) {
return;
}
}
/**
*
*/
-(void)onGameStarted {
NSLog(@"ISudFSMMG:onGameStarted:游戏开始");
}
/**
*
*/
-(void) onGameDestroyed {
NSLog(@"ISudFSMMG:onGameDestroyed:游戏开始");
}
/**
* Code
* @param dataJson {"code":"value"}
*/
-(void)onExpireCode:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
NSLog(@"ISudFSMMG:onExpireCode:Code过期");
//
[Api getSudGameCode:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code == 200) {
NSString * gameCode = data.data[@"code"];
self.code = gameCode;
[self.fsmAPP2MG updateCode:gameCode listener:^(int retCode, const NSString *retMsg, const NSString *dataJson) {
NSLog(@"ISudFSMMG:updateGameCode retCode=%@ retMsg=%@ dataJson=%@", @(retCode), retMsg, dataJson);
}];
//
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onExpireCode", @"ret_msg", nil];
[handle success:[SudCommon dictionaryToJson:dict]];
} else {
[XCHUDTool showErrorWithMessage:msg];
}
} uid:[AccountInfoStorage instance].getUid];
}
/**
* View
* @param handle
* @param dataJson {}
*/
-(void)onGetGameViewInfo:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
CGRect rect = [[UIScreen mainScreen] bounds];
CGFloat scale = [[UIScreen mainScreen] nativeScale];
CGFloat top = (kNavigationHeight+95) * scale;
CGFloat bottom;
if (iPhoneXSeries) {
bottom = (47+kSafeAreaBottomHeight+30 + 70) * scale;
} else {
bottom = (47+10+70) * scale;
}
CGFloat width = rect.size.width * scale;
CGFloat height = rect.size.height * scale;
NSDictionary *rectDict = [NSDictionary dictionaryWithObjectsAndKeys:@(top), @"top", @(0), @"left", @(bottom), @"bottom", @(0), @"right", nil];
NSDictionary *viewDict = [NSDictionary dictionaryWithObjectsAndKeys:@(width), @"width", @(height), @"height", nil];
NSDictionary *dataDict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onGetGameViewInfo", @"ret_msg", viewDict, @"view_size", rectDict, @"view_game_rect", nil];
///
[handle success:[SudCommon dictionaryToJson:dataDict]];
}
/**
*
* @param handle
* @param dataJson {}
*/
-(void)onGetGameCfg:(id<ISudFSMStateHandle>)handle dataJson:(NSString*)dataJson {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"ret_code"] = @(0);
dict[@"ret_msg"] = @"return form APP onGetGameCfg";
dict[@"ui"] = @{
@"join_btn" : @{@"custom": @(YES), @"hide": @(NO)},//
@"start_btn" : @{@"custom": @(YES), @"hide": @(NO)},//
@"lobby_players" : @{@"custom": @(YES), @"hide": @(NO)},//
@"level" : @{@"custom": @(YES), @"hide" : @(YES)},//
};
NSString *dataJsonRet = @"";
NSData *dataJsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
if (dataJsonData != nil) {
dataJsonRet = [[NSString alloc]initWithData:dataJsonData encoding:NSUTF8StringEncoding];
}
[handle success:dataJsonRet];
}
/**
*
* @param handle
* @param state
* @param dataJson json
*/
-(void)onGameStateChange:(id<ISudFSMStateHandle>) handle state:(NSString*) state dataJson:(NSString*) dataJson {
if ([state isEqualToString:MG_COMMON_PUBLIC_MESSAGE]) {
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:公屏消息");
} else if ([state isEqualToString:MG_COMMON_KEY_WORD_TO_HIT]) {
NSDictionary *dic = [SudCommon turnStringToDictionary:dataJson];
NSString *word = [dic objectForKey:@"word"];
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:你画我猜关键词获取:%@",word);
///
self.DrawSomethingKeyWord = word;
if (word == (id) [NSNull null] || [word isEqualToString:@""]) {
/// hit
self.keyWordHiting = NO;
} else {
/// hit
self.keyWordHiting = YES;
}
}else if ([state isEqualToString:MG_COMMON_SELF_CLICK_JOIN_BTN]) {//
NSDictionary *dic = [SudCommon turnStringToDictionary:dataJson];
int seatIndex = -1;
if ([dic objectForKey:@"seatIndex"]) {
seatIndex = [[dic objectForKey:@"seatIndex"] intValue];
}
if (seatIndex == -1) {
NSLog(@"来自加入按钮%d",seatIndex);
}else {
NSLog(@"来自麦位+入%d",seatIndex);
}
if ([self isOnMicro:[AccountInfoStorage instance].getUid.integerValue]) {//
[self notifySelfInState:YES seatIndex:seatIndex];
} else {
//
[self upMicToJoinGame];
}
} else if([state isEqualToString:MG_COMMON_SELF_CLICK_START_BTN]) {//
[self notifyIsPlayingState:YES];
} else if ([state isEqualToString:MG_COMMON_SELF_CLICK_CANCEL_JOIN_BTN]) {
/// 退
[self handleSelfInExitEvent];
} else {
///
NSLog(@"ISudFSMMG:onGameStateChange:游戏->APP:state:%@",MG_COMMON_PUBLIC_MESSAGE);
}
}
/**
*
* @param handle
* @param userId id
* @param state
* @param dataJson JSON
*/
-(void)onPlayerStateChange:(nullable id<ISudFSMStateHandle>) handle userId:(NSString*) userId state:(NSString*) state dataJson:(NSString*) dataJson {
NSLog(@"ISudFSMMG:onPlayerStateChange:游戏->APP:游戏玩家状态变化:userId: %@ --state: %@ --dataJson: %@", userId, state, dataJson);
///
NSString *dataStr = @"";
if ([state isEqualToString:MG_COMMON_PLAYER_IN]) {
dataStr = @"玩家: 加入状态";
[self handleState_MG_COMMON_PLAYER_IN_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_READY]) {
dataStr = @"玩家: 准备状态";
[self handleState_MG_COMMON_PLAYER_READY_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_CAPTAIN]) {
dataStr = @"玩家: 队长状态";
[self handleState_MG_COMMON_PLAYER_CAPTAIN_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_COMMON_PLAYER_PLAYING]) {
dataStr = @"玩家: 游戏状态";
[self handleState_MG_COMMON_PLAYER_PLAYING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_SELECTING]) {
dataStr = @"你画我猜 玩家: 选词中";
[self handleState_MG_DG_SELECTING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_PAINTING]) {
dataStr = @"你画我猜 玩家: 作画中";
[self handleState_MG_DG_PAINTING_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_ERRORANSWER]) {
dataStr = @"你画我猜 玩家: 错误答";
[self handleState_MG_DG_ERRORANSWER_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_TOTALSCORE]) {
dataStr = @"你画我猜 玩家: 总积分";
[self handleState_MG_DG_TOTALSCORE_WithUserId:userId dataJson:dataJson];
} else if ([state isEqualToString:MG_DG_SCORE]) {
dataStr = @"你画我猜 玩家: 本次积分";
[self handleState_MG_DG_SCORE_WithUserId:userId dataJson:dataJson];
}else {
NSLog(@"ISudFSMMG:onPlayerStateChange:未做解析状态:%@", MG_DG_SCORE);
}
NSLog(@"ISudFSMMG:onPlayerStateChange:dataStr:%@", dataStr);
///
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@(0), @"ret_code", @"return form APP onPlayerStateChange", @"ret_msg", nil];
[handle success:[SudCommon dictionaryToJson:dict]];
}
/// 退
- (void)handleSelfInExitEvent {
/// 退
if ([self isInSudGame]) {
[self notifyIsPlayingState:false];
[self nofityPlayerPlaying:NO];
[self notifySetReady:false];
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
} else if ([self getCurrentUserSudGameStatus] == LittleGamePlayStatus_Ready) { ///
/// 退
[self notifySetReady:false];
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
} else {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
}
///
[self notifySelfInState:false seatIndex:-1];
}
///
- (void)handleSelfReadyEvent {
[self notifySetReady:true];
}
///
- (void)handleSelfCancelReadyEvent {
[self notifySetReady:false];
}
///
- (void)handleGameStartEvent {
[self notifyIsPlayingState:YES];
}
#pragma mark =======APP->=======
/// app to mg
/// @param state
/// @param dataJson json
- (void)notifyStateChange:(NSString *) state dataJson:(NSString*) dataJson {
[self.fsmAPP2MG notifyStateChange:state dataJson:dataJson listener:^(int retCode, const NSString *retMsg, const NSString *dataJson) {
NSLog(@"ISudFSMMG:notifyStateChange:retCode=%@ retMsg=%@ dataJson=%@", @(retCode), retMsg, dataJson);
RoomInfoModel * roomInfo = self.hostDelegate.getRoomInfo;
if (retCode == 0 && [state isEqualToString:APP_COMMON_SELF_PLAYING]) {//
//
NSString *mgid = [NSString stringWithFormat:@"%lld", self.currentmgId];
if (mgid.length <= 0) {
return;
}
[Api startGameCheck:^(BaseModel * _Nullable data, NSInteger code, NSString * _Nullable msg) {
if (code != 200) {
[XCHUDTool showErrorWithMessage:msg];
}
} roomUid:[NSString stringWithFormat:@"%ld", roomInfo.uid] mgId:mgid];
} else if (retCode == 0 && [state isEqualToString:APP_COMMON_SELF_END]) {//
self.isPlaying = NO;
}
}];
}
/// ,退
/// @param isIn YES: NO:退
- (void)notifySelfInState:(BOOL)isIn uid:(NSInteger)uid {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isIn), @"isIn", @(1), @"teamId", nil];
[self notifyStateChange:APP_COMMON_SELF_IN dataJson:[SudCommon dictionaryToJson:dic]];
}
/// ,退
/// @param isIn YES: NO:退
- (void)notifySelfInState:(BOOL)isIn seatIndex:(int)seatIndex {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(seatIndex), @"seatIndex", @(isIn), @"isIn", @(1), @"teamId", nil];
[self notifyStateChange:APP_COMMON_SELF_IN dataJson:[SudCommon dictionaryToJson:dic]];
}
///
/// @param userId id
- (void)notifyKickStateWithUserId:(NSString *)userId {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:userId, @"kickedUID", nil];
[self notifyStateChange:APP_COMMON_SELF_KICK dataJson:[SudCommon dictionaryToJson:dic]];
}
///
/// @param userId id
- (void)notifySetCaptainStateWithUserId:(NSString *)userId {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:userId, @"curCaptainUID", nil];
[self notifyStateChange:APP_COMMON_SELF_CAPTAIN dataJson:[SudCommon dictionaryToJson:dic]];
}
///
- (void)notifyChangeTextHitState:(NSString *)keyWord {
if (keyWord.length && [keyWord containsString:self.DrawSomethingKeyWord]) {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(true), @"isHit", self.DrawSomethingKeyWord, @"keyWord", self.DrawSomethingKeyWord, @"text", nil];
[self notifyStateChange:APP_COMMON_SELF_TEXT_HIT dataJson:[SudCommon dictionaryToJson:dic]];
}
}
///
- (void)notifySetReady:(BOOL)isReady {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isReady), @"isReady", nil];
[self notifyStateChange:APP_COMMON_SELF_READY dataJson:[SudCommon dictionaryToJson:dic]];
}
///
- (void)notifySetEnd {
[self notifyStateChange:APP_COMMON_SELF_END dataJson:[SudCommon dictionaryToJson:@{}]];
}
///
- (void)notifyIsPlayingState:(BOOL)isPlaying {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isPlaying), @"isPlaying", nil];
[self notifyStateChange:APP_COMMON_SELF_PLAYING dataJson:[SudCommon dictionaryToJson:dic]];
}
///退
- (void)nofityPlayerPlaying:(BOOL)isPlaying {
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(isPlaying), @"isPlaying", nil];
[self notifyStateChange:MG_COMMON_PLAYER_PLAYING dataJson:[SudCommon dictionaryToJson:dic]];
}
#pragma mark =======->APP=======
- (void)handleState_MG_COMMON_PLAYER_IN_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
/// YESNO退
BOOL isIn = NO;
if (dic) {
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isIn = [[dic objectForKey:@"isIn"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {//
if (isIn) {//
//
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
} else {//
[self upMicToJoinGame];
}
//
if (self.hostDelegate.getRoomInfo.uid == userId.integerValue) {
[self notifySetCaptainStateWithUserId:userId];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}else {//退
//
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_NoIn];
}
self.sudGameStatus = LittleGamePlayStatus_NoIn;
}
} else {//退
if (self.sudGameStatus == LittleGamePlayStatus_Plying) {//退
NIMChatroomMembersByIdsRequest *request = [[NIMChatroomMembersByIdsRequest alloc]init];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.userIds = @[[AccountInfoStorage instance].getUid];
[[NIMSDK sharedSDK].chatroomManager fetchChatroomMembersByIds:request completion:^(NSError * _Nullable error, NSArray<NIMChatroomMember *> * _Nullable members) {
if (error == nil) {
NIMChatroomMember *member = members.firstObject;
if (member.type == NIMChatroomMemberTypeManager || member.type == NIMChatroomMemberTypeCreator) {
NIMChatroomMembersByIdsRequest *request = [[NIMChatroomMembersByIdsRequest alloc]init];
request.roomId = [NSString stringWithFormat:@"%ld", self.hostDelegate.getRoomInfo.roomId];
request.userIds = @[userId];
[[NIMSDK sharedSDK].chatroomManager fetchChatroomMembersByIds:request completion:^(NSError * _Nullable error, NSArray<NIMChatroomMember *> * _Nullable members) {
if (error == nil) {
NIMChatroomMember *member = members.firstObject;
[XCHUDTool showErrorWithMessage:[NSString stringWithFormat:@"%@退出了游戏", member.roomNickname]];
}
}];
}
}
}];
}
}
}
- (void)handleState_MG_COMMON_PLAYER_READY_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// ,YES:NO:
BOOL isReady = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isReady = [[dic objectForKey:@"isReady"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {
if (isReady) {
//
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_Ready];
}
self.sudGameStatus = LittleGamePlayStatus_Ready;
}else {
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}
}
}
- (void)handleState_MG_COMMON_PLAYER_CAPTAIN_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
/// YES NO
BOOL isCaptain = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
///
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isCaptain = [[dic objectForKey:@"isCaptain"] boolValue];
}
}
- (void)handleState_MG_COMMON_PLAYER_PLAYING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
///
BOOL isPlaying = NO;
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
if (dic) {
///
NSInteger retCode = [[dic objectForKey:@"retCode"] integerValue];
if (retCode != 0) {
return;
}
isPlaying = [[dic objectForKey:@"isPlaying"] boolValue];
}
if ([userId isEqualToString:[AccountInfoStorage instance].getUid]) {
self.isPlaying = isPlaying;
if (isPlaying) {
//
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_Plying];
}
///
[self.littleGameMiniView hideSudGamePostionView];
self.sudGameStatus = LittleGamePlayStatus_Plying;
}else {
if ([self isOnMicro:[userId longLongValue]]) {
[self updateMicInfoWithGameStatus:LittleGamePlayStatus_IsIn];
}
self.sudGameStatus = LittleGamePlayStatus_IsIn;
}
}
}
- (void)handleState_MG_DG_SELECTING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSLog(@"handleState_MG_DG_SELECTING_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_PAINTING_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
NSLog(@"handleState_MG_DG_PAINTING_WithUserId%@",dataJson);
///
NSDictionary * dic = [SudCommon turnStringToDictionary:dataJson];
bool isPainting = NO;
if (dic) {
isPainting = [dic[@"isPainting"] boolValue];
}
}
- (void)handleState_MG_DG_ERRORANSWER_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
///
NSLog(@"handleState_MG_DG_ERRORANSWER_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_TOTALSCORE_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
///
NSLog(@"handleState_MG_DG_TOTALSCORE_WithUserId%@",dataJson);
}
- (void)handleState_MG_DG_SCORE_WithUserId:(NSString *)userId dataJson:(NSString *)dataJson {
///
NSLog(@"handleState_MG_DG_SCORE_WithUserId%@",dataJson);
}
/// MG
- (void)destroyMG {
[self.fsmAPP2MG destroyMG];
}
#pragma mark - RoomGuestDelegate
- (void)onRoomEntered {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
self.hidden = YES;
return;
} else {
self.hidden = NO;
}
[self updateSudGame];
}
- (void)onRoomUpdate {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
self.hidden = YES;
} else {
self.hidden = NO;
}
[self updateSudGame];
}
#pragma mark - RoomGuestDelegate
- (void)onMicroQueueUpdate:(NSMutableDictionary<NSString *,MicroQueueModel *> *)queue {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
return;
}
if (self.hostDelegate.getRoomInfo.type == RoomType_MiniGame) {
[self.littleGameMiniView needRefreshPosition:queue];
}
}
- (void)handleNIMCustomMessage:(NIMMessage *)message {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
return;
}
NIMCustomObject *obj = (NIMCustomObject *)message.messageObject;
if (obj.attachment != nil && [obj.attachment isKindOfClass:[AttachmentModel class]]) {
AttachmentModel *attachment = (AttachmentModel *)obj.attachment;
if (attachment.first == CustomMessageType_Kick_User) {
XPKickUserModel * kickModel = [XPKickUserModel modelWithJSON:attachment.data];
[self onDownMic:kickModel.uid];
} else if(attachment.first == CustomMessageType_Queue && attachment.second == Custom_Message_Sub_Queue_Kick) {
XPKickUserModel * kickModel = [XPKickUserModel modelWithJSON:attachment.data];
[self onDownMic:kickModel.uid];
}
}
}
- (void)handleNIMNotificationMessage:(NIMMessage *)message {
if (self.hostDelegate.getRoomInfo.type != RoomType_MiniGame) {
return;
}
NIMNotificationObject *notiMsg = (NIMNotificationObject *)message.messageObject;
NIMChatroomNotificationContent *content = (NIMChatroomNotificationContent *)notiMsg.content;
switch (content.eventType) {
case NIMChatroomEventTypeQueueChange: //
{
NSDictionary* data = (NSDictionary *)content.ext;
UserInfoModel* userInfo = [UserInfoModel modelWithJSON:[data objectForKey:NIMChatroomEventInfoQueueChangeItemValueKey]];
NSInteger changeType = [data[NIMChatroomEventInfoQueueChangeTypeKey] integerValue];
if (changeType != 1) {
[self onDownMic:userInfo.uid];
}
}
break;
default:
break;
}
}
#pragma mark - Getters And Setters
- (XPLittleGameMiniStageView *)littleGameMiniView {
if (!_littleGameMiniView) {
_littleGameMiniView = [[XPLittleGameMiniStageView alloc] init];
}
return _littleGameMiniView;
}
@end

View File

@@ -197,7 +197,7 @@
make.top.mas_equalTo(self.shareButton);
}];
}
self.gameListView.mgId = roomInfo.mgId.integerValue > 0 ? roomInfo.mgId : @"-1";
self.gameListView.mgId = roomInfo.mgId > 0 ? [NSString stringWithFormat:@"%lld", roomInfo.mgId] : @"-1";
} else {
if (self.gameListView.superview) {
[self.gameListView removeFromSuperview];

View File

@@ -34,6 +34,30 @@
}];
}
- (void)configMicroView:(MicroQueueModel *)model {
[super configMicroView:model];
UserInfoModel * info = model.userInfo;
self.stateButton.hidden = NO;
if (info.uid == self.getRoomInfo.uid) {//
[self.stateButton setTitle:@"房主" forState:UIControlStateNormal];
[self.stateButton setBackgroundColor:UIColorFromRGB(0x20AAF5)];
} else {
if (info.gameStatus == LittleGamePlayStatus_NoIn) { //
self.stateButton.hidden = YES;
} else if (info.gameStatus == LittleGamePlayStatus_IsIn) {
[self.stateButton setTitle:@"未准备" forState:UIControlStateNormal];
[self.stateButton setBackgroundColor:UIColorFromRGB(0xFFA936)];
} else if (info.gameStatus == LittleGamePlayStatus_Ready) {
[self.stateButton setTitle:@"已准备" forState:UIControlStateNormal];
[self.stateButton setBackgroundColor:UIColorFromRGB(0x56D41A)];
} else if (info.gameStatus == LittleGamePlayStatus_Plying) {
[self.stateButton setTitle:@"游戏中" forState:UIControlStateNormal];
[self.stateButton setBackgroundColor:UIColorFromRGB(0x56D41A)];
} else {
self.stateButton.hidden = YES;
}
}
}
#pragma mark - Getters And Setters
- (UIButton *)stateButton {

View File

@@ -26,6 +26,8 @@ NS_ASSUME_NONNULL_BEGIN
@property (nonatomic, copy) NSString *micCircle;
///麦位昵称颜色
@property (nonatomic, copy) NSString *micNickColor;
/// 小游戏状态 0 未加入游戏1 加入游戏未准备2 加入游戏已准备 3 游戏中
@property (nonatomic, assign) LittleGamePlayStatus gameStatus;
@end
NS_ASSUME_NONNULL_END

View File

@@ -43,6 +43,7 @@
#import "XPRoomSettingInputView.h"
#import "XPReleaseRadioViewController.h"
#import "XPRoomTrumpetViewController.h"
#import "XPRoomLittleGameContainerView.h"
///P
#import "XPRoomPresenter.h"
#import "XPRoomProtocol.h"
@@ -73,6 +74,8 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
@property (nonatomic,strong) XPRoomAnimationView *animationView;
///view
@property (nonatomic,strong) XPRoomFunctionContainerView *functionView;
///
@property (nonatomic,strong) XPRoomLittleGameContainerView *littleGameView;
///Uid
@property (nonatomic,copy) NSString * roomUid;
///id
@@ -161,6 +164,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
#pragma mark - Private Method
- (void)initSubViews {
[self.view addSubview:self.backContainerView];
[self.view addSubview:self.littleGameView];
[self.view addSubview:self.stageView];
[self.view addSubview:self.messageContainerView];
[self.view addSubview:self.menuContainerView];
@@ -213,6 +217,10 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.functionView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self.view);
}];
[self.littleGameView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(self.view);
}];
}
- (void)exitOldRoom {
@@ -279,7 +287,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
}
if (!self.stageView.superview) {
[self.view insertSubview:self.stageView aboveSubview:self.roomHeaderView];
[self.view insertSubview:self.stageView belowSubview:self.roomHeaderView];
}
[self.stageView mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(self.view);
@@ -402,6 +410,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.activityContainerView onRoomEntered];
[self.menuContainerView onRoomEntered];
[self.backContainerView onRoomEntered];
[self.littleGameView onRoomEntered];
if ([XPRoomMiniManager shareManager].getRoomInfo.uid != self.roomUid.integerValue) {// 退
[self.presenter enterNIMRoom:[NSString stringWithFormat:@"%ld", self.roomInfo.roomId] user:self.userInfo];
[self.functionView onRoomEntered];
@@ -439,6 +448,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.roomHeaderView onRoomUpdate];
[self.activityContainerView onRoomUpdate];
[self.backContainerView onRoomUpdate];
[self.littleGameView onRoomEntered];
[self.presenter enterNIMRoom:[NSString stringWithFormat:@"%ld", self.roomInfo.roomId] user:self.userInfo];
}
@@ -522,6 +532,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.menuContainerView onRoomUpdate];
[self.functionView onRoomUpdate];
[self.activityContainerView onRoomUpdate];
[self.littleGameView onRoomUpdate];
}
break;
}
@@ -563,6 +574,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.activityContainerView handleNIMNotificationMessage:message];
[self.menuContainerView handleNIMNotificationMessage:message];
[self.functionView handleNIMNotificationMessage:message];
[self.littleGameView handleNIMNotificationMessage:message];
} else if (message.messageType == NIMMessageTypeCustom) {
NIMCustomObject *obj = (NIMCustomObject *)message.messageObject;
if (obj.attachment != nil && [obj.attachment isKindOfClass:[AttachmentModel class]]) {
@@ -572,6 +584,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
[self.menuContainerView handleNIMCustomMessage:message];
[self.activityContainerView handleNIMCustomMessage:message];
[self.functionView handleNIMCustomMessage:message];
[self.littleGameView handleNIMCustomMessage:message];
if (attachment.first == CustomMessageType_First_Recharge_Reward && attachment.second == Custom_Message_Sub_Room_First_Recharge_Reward) {
self.userInfo.isFirstCharge = NO;
[self.menuContainerView onRoomUpdate];
@@ -709,7 +722,7 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
- (void)onMicroQueueUpdate:(NSMutableDictionary<NSString *,MicroQueueModel *> *)queue {
[self.menuContainerView onMicroQueueUpdate:queue];
[self.functionView onRoomUpdate];
[self.functionView onMicroQueueUpdate:queue];
[self.littleGameView onMicroQueueUpdate:queue];
}
- (void)onMicroGiftValueUpdate:(NSDictionary *)data {
@@ -804,4 +817,11 @@ UIKIT_EXTERN NSString * const kRoomMiniNotificationKey;
return _stageView;
}
- (XPRoomLittleGameContainerView *)littleGameView {
if (!_littleGameView) {
_littleGameView = [[XPRoomLittleGameContainerView alloc] initWithDelegate:self];
}
return _littleGameView;
}
@end