Files
youle_app_ios/msext/Class/RootVC/gameController.m
joywayer 93b1881e52 feat: 优化分享功能和剪贴板管理
- 修改gameController分享逻辑,支持不同分享类型
- 新增PasteboardManager类,优化iOS 14+剪贴板访问
- 减少剪贴板权限弹窗,提升用户体验
2025-06-17 20:53:07 +08:00

2556 lines
108 KiB
Objective-C
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// gameController.m
// msext
//
// Created by chao on 2017/8/16.
// Copyright © 2017年 chao. All rights reserved.
//
#import "gameController.h"
#import "WXApiManager.h"
#import "WXApiRequestHandler.h"
#import "NSString+SBJSON.h"
#import "SBJSON.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import "AFNetworking.h"
#import "GDataXMLNode.h"
#import "ASIHTTPRequest.h"
#import "ZipArchive.h"
#import "threeView.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "VoiceConverter.h"
#import "ChatVoiceRecorderVC.h"
#import <Bugly/Bugly.h>
#import "Reachability.h"
#import "WebViewJavascriptBridge.h"
#import "gameController.h"
#import "HTTPServer.h"
#import "versionConfig.h"
#define DefaultLocationTimeout 10
#define DefaultReGeocodeTimeout 5
#import <AgoraRtcEngineKit/AgoraRtcEngineKit.h>
#import "AppID.h"
#import <CommonCrypto/CommonDigest.h>
#import <AdSupport/ASIdentifierManager.h>
#import "XianliaoApiManager.h"
#import "QiniuManager.h"
#import "QiniuConfig.h"
#import "SharePanel.h"
#import "WechatShareManager.h"
@interface gameController ()
<WKNavigationDelegate,WXApiManagerDelegate,VoiceRecorderBaseVCDelegate,AVAudioPlayerDelegate,ASIHTTPRequestDelegate,AMapLocationManagerDelegate,UIActionSheetDelegate,AgoraRtcEngineDelegate>
{
WKWebView *_webView;
NSString *versionURL;
AVAudioPlayer *backgroundPlayer;
AVAudioPlayer *buttunPlayer;
AVAudioPlayer *voicePlayer;
SystemSoundID sound;
ChatVoiceRecorderVC *recorderVC;
NSURLSessionDownloadTask *_downloadTask;
UIImageView *background,*proimageView;
UILabel *prolabel;
UIProgressView *pro_Download;
NSProgress *pro;
BOOL canshake,canvoice;
BOOL firsttime,canbofang,first_Time,Nothere;
NSMutableArray * players;
AgoraRtcVideoCanvas *videoCanvas1,*videoCanvas2,*videoCanvas3,*videoCanvas4,*videoCanvas5;
UIView *localVideo;
UIView *localVideoBG;
UIView *remoteVideo1;
BOOL isInView;
UIView *remote1;
CGPoint beginpoint;
}
@property (strong, nonatomic) NSString *recordFileName,*recordFilePath;
@property (copy, nonatomic) NSString *originWav;
@property (copy, nonatomic) NSString *backgroundType;
@property (copy, nonatomic) NSString *User_id,*UserType;
@property (copy, nonatomic) NSString *game_name;
@property (copy, nonatomic) NSString *gamefilepath;
@property (copy, nonatomic) NSString *downLoadfile;
@property (copy, nonatomic) NSString *agentinfo,*gameinfo,*versioninfo;
@property (copy, nonatomic) NSString *market,*channel_id,*tuiguang_id ;
@property (copy, nonatomic) NSArray *agentlist;
@property (copy, nonatomic) NSArray *gamelist;
@property (copy, nonatomic) NSDictionary *magentlist,*mgamelist;
@property (nonatomic, strong) CTCallCenter *callCenter;
@property (nonatomic) BOOL callWasStarted;
@property (copy, nonatomic) NSString *dataofgame;
@property (copy, nonatomic) NSString *showmessage;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@property (copy, nonatomic) NSString *game_version_,*game_zip_,*gameconfig;
@property (nonatomic) int netstate,result_state;
@property (copy, nonatomic) NSString *openweb;
@property (nonatomic,strong) HTTPServer *localHttpServer;
@property (nonatomic,copy) NSString *port;
@property WebViewJavascriptBridge* bridge;
@property (strong, nonatomic) AgoraRtcEngineKit *agoraKit;
@end
@implementation gameController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.view.backgroundColor=[UIColor colorWithRed:255.0f/255 green:255.0f/255 blue:255.0f/255 alpha:1.0f];
}
return self;
}
/* system class */
/* system class */
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (!isInView) // 仅当取到touch的view是小窗口时我们才响应触控否则直接return
{
return;
}
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:localVideoBG];
//偏移量
float offsetX = currentPosition.x - beginpoint.x;
float offsetY = currentPosition.y - beginpoint.y;
//移动后的中心坐标
localVideoBG.center = CGPointMake(localVideoBG.center.x + offsetX, localVideoBG.center.y + offsetY);
//x轴左右极限坐标
if (localVideoBG.center.x > (localVideoBG.superview.frame.size.width-localVideoBG.frame.size.width/2))
{
CGFloat x = localVideoBG.superview.frame.size.width-localVideoBG.frame.size.width/2;
localVideoBG.center = CGPointMake(x, localVideoBG.center.y + offsetY);
}
else if (localVideoBG.center.x < localVideoBG.frame.size.width/2)
{
CGFloat x = localVideoBG.frame.size.width/2;
localVideoBG.center = CGPointMake(x, localVideoBG.center.y + offsetY);
}
//y轴上下极限坐标
if (localVideoBG.center.y > (localVideoBG.superview.frame.size.height-localVideoBG.frame.size.height/2))
{
CGFloat x = localVideoBG.center.x;
CGFloat y = localVideoBG.superview.frame.size.height-localVideoBG.frame.size.height/2;
localVideoBG.center = CGPointMake(x, y);
}
else if (localVideoBG.center.y <= localVideoBG.frame.size.height/2)
{
CGFloat x = localVideoBG.center.x;
CGFloat y = localVideoBG.frame.size.height/2;
localVideoBG.center = CGPointMake(x, y);
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if (touch.view.frame.size.width == 214) // 120为小窗口的宽度简单起见这里使用硬编码示例用来判断触控范围;仅当取到touch的view是小窗口时我们才响应触控
{
isInView = YES;
}
else
{
isInView = NO;
}
beginpoint = [touch locationInView:localVideoBG];
[super touchesBegan:touches withEvent:event];
}
-(void) viewDidAppear:(BOOL)animated
{
}
-(BOOL)canBecomeFirstResponder
{
return YES;
}
#pragma mark -- 本地服务器 --
#pragma mark -服务器
#pragma mark - 搭建本地服务器 并且启动
-(void)initView
{
self.gameconfig= [FuncPublic filename:@"gameconfig"];
self.tuiguang_id= [FuncPublic filename:@"tuiguang"];
[self initJSdata];
if(1)
{
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/app_gamesname.js", [FuncPublic filename:@"gamedir"], [FuncPublic filename:@"gamestart"]] PathType:2];
NSError *error = nil;
NSString *str = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if([str rangeOfString:[NSString stringWithFormat:@"%@",self.game_name]].location ==NSNotFound)
{
NSLog(@"yes");
// NSString *info=[NSString stringWithFormat:@"var app_gamesname=new Array('%@');", [FuncPublic filename:@"gamestart"]];
str= [str stringByReplacingOccurrencesOfString:@")" withString:[NSString stringWithFormat:@",'%@')",self.game_name]];
NSData *txtData=[str dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager]createFileAtPath:filePath contents:txtData attributes:nil];
}
}
// Do any additional setup after loading the view from its nib.
@try{
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/index.html",self.gamefilepath,self.game_name] PathType:2];
// NSString * filePathString = [filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL fileURLWithPath:filePath];
if (self.openweb==nil||[self.openweb intValue]==0) {
[_webView loadFileURL:url allowingReadAccessToURL:[NSURL fileURLWithPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@",self.gamefilepath,self.game_name] PathType:2]]];
}else
{
_localHttpServer = [[HTTPServer alloc] init];
[_localHttpServer setType:@"_http.tcp"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]){
NSLog(@">>>> File path error!");
}else{
NSString *webLocalPath = webPathtcp;
[_localHttpServer setDocumentRoot:webLocalPath];
NSLog(@">>webLocalPath:%@",webLocalPath);
NSError *error;
if([_localHttpServer start:&error]){
NSLog(@"Started HTTP Server on port %hu", [_localHttpServer listeningPort]);
self.port = [NSString stringWithFormat:@"%d",[_localHttpServer listeningPort]];
}
else{
NSLog(@"Error starting HTTP Server: %@", error);
}
}
NSString *str = [NSString stringWithFormat:@"http://localhost:%@", self.port];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
//初始化偏好设置属性preferences
config.preferences = [WKPreferences new];
//The minimum font size in points default is 0;
config.preferences.minimumFontSize = 10;
//是否支持JavaScript
config.preferences.javaScriptEnabled = YES;
//不通过用户交互,是否可以打开窗口
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
WKWebView* _webView12 = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, DEVW, DEVH) configuration:config];
_webView12.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:_webView12];
_webView12.navigationDelegate = self;
[_webView12 loadRequest:request];
}
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"webViewDidStartLoad");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"webViewDidFinishLoad");
if(prolabel!=nil)
{
[UIView beginAnimations:@"FrameAni"context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
// [UIViewsetAnimationWillStartSelector:@selector(startAni:)];
[UIView setAnimationDidStopSelector:@selector(stopAni:)];
[UIView setAnimationRepeatCount:1];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
proimageView.alpha=0;
prolabel.alpha=0;
[UIView commitAnimations];
}
}
-(void)stopAni:(NSString*)aniID{
NSLog(@"%@stop",aniID);
[prolabel removeFromSuperview];
[proimageView removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
// [FuncPublic ShowAlert:@"系统内存不够,请清理应用数据,或者重启应用"];
}
//支持的方向 因为界面A我们只需要支持竖屏
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscape;
}
-(BOOL)shouldAutorotate{
return YES;
}
//当前viewcontroller默认的屏幕方向 - 横屏显示
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return UIInterfaceOrientationLandscapeRight;
}
-(void)dealloc
{
if (backgroundPlayer!=nil) {
backgroundPlayer.numberOfLoops = 0;
[backgroundPlayer stop];
backgroundPlayer = nil;
}
_completionBlock=nil;
_bridge=nil;
_webView=nil;
recorderVC=nil;
}
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert"message:@"JS调用alert"preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]];
[self presentViewController:alert animated:YES completion:NULL];
NSLog(@"%@", message);
}
- (void)viewDidLoad {
if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) {
self.edgesForExtendedLayout = UIRectEdgeNone;
}
[super viewDidLoad];
NSLog(@"第一个");
[UIApplication sharedApplication].idleTimerDisabled=YES;
firsttime=YES; first_Time=YES; canbofang=YES;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0,DEVW ,DEVH )];
_webView.navigationDelegate = self;
[self.view addSubview: _webView];
if (@available(ios 11.0,*))
{
UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
[WebViewJavascriptBridge enableLogging];
_bridge = [WebViewJavascriptBridge bridgeForWebView:_webView];
[_bridge setWebViewDelegate:self];
[_bridge registerHandler:@"accreditlogin" handler:^(id data, WVJBResponseCallback responseCallback) {
[WXApiRequestHandler sendAuthRequestScope: kAuthScope State:kAuthState OpenID:kAuthOpenID InViewController:self];
responseCallback(@"Response from accreditlogin");
}];
[_bridge registerHandler:@"srcIsloop" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Callback called: %@", data);
NSString *message2=[data objectForKey:@"isloop"];
NSString *message=[data objectForKey:@"src"];
NSURL *url_=nil;
NSString * string=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/assets/wav/%@",self.gamefilepath,self.game_name,message] PathType:2];
url_=[NSURL URLWithString:string];
if([message2 intValue]==0)
{
// if (buttunPlayer!=nil) {
// [buttunPlayer stop];
// buttunPlayer = nil;
// }
buttunPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil];
[buttunPlayer prepareToPlay];
// buttunPlayer.numberOfLoops =1;
[buttunPlayer play];
return ;
// AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// NSError *err = nil;
//
// NSError *audioError = nil;
// BOOL success = [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&audioError];
// if(!success)
// {
// NSLog(@"error doing outputaudioportoverride - %@", [audioError localizedDescription]);
// }
// [audioSession setCategory :AVAudioSessionCategoryAudioProcessing error:&err];
// AudioServicesCreateSystemSoundID((__bridge CFURLRef)url_,&shake_sound_male_id);
// AudioServicesPlaySystemSound(shake_sound_male_id);
}
if([message2 intValue]==1)
{
self.backgroundType=message;
if (backgroundPlayer!=nil) {
backgroundPlayer.numberOfLoops = 0;
[backgroundPlayer stop];
backgroundPlayer = nil;
}
backgroundPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil];
// backgroundPlayer.delegate = self;
[backgroundPlayer prepareToPlay];
backgroundPlayer.numberOfLoops = -1;
[backgroundPlayer play];
}
if([message2 intValue]==-1)
{
if ([self.backgroundType isEqualToString:message]) {
if (backgroundPlayer!=nil) {
backgroundPlayer.numberOfLoops = 0;
[backgroundPlayer stop];
backgroundPlayer = nil;
}
}
}
responseCallback(@"Response from srcIsloop");
}];
[_bridge registerHandler:@"prepareaudio" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Callback called: %@", data);
self.originWav =[VoiceRecorderBaseVC getCurrentTimeString];//[dateformat stringFromDate:[NSDate date]];//
if([FuncPublic ifauth]==0)
{
NSString* runJS=[NSString stringWithFormat:@"%@需要访问您的麦克风,请启用麦克风-设置/隐私/麦克风!",gamehallname];
[FuncPublic ShowAlert:runJS];
return;
}
//开始录音
[recorderVC beginRecordByFileName:self.originWav];
responseCallback(@"Response from prepareaudio");
}];
[_bridge registerHandler:@"mediaTypeAudio" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"Callback called: %@", data);
NSString *url=[data objectForKey:@"audiourl"];
// NSString *history=[data objectForKey:@"type"];
NSString *userid=[data objectForKey:@"user"];
self.User_id=userid;
self.recordFileName = [FuncPublic GetCurrentTimeString];
NSURL *urlPath = [NSURL URLWithString:url];
NSData *data_url = [NSData dataWithContentsOfURL:urlPath];
NSString *filename = [FuncPublic GetPathByFileName:self.recordFileName ofType:@"amr"];
[data_url writeToFile: filename atomically: NO];
if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) {
return;
}
//获取路径
self.recordFilePath = [FuncPublic GetPathByFileName:self.recordFileName ofType:@"wav"];
NSString *convertedPath = [FuncPublic GetPathByFileName:[self.recordFileName stringByAppendingString:@"_AmrToWav"] ofType:@"wav"];
if ([VoiceConverter ConvertAmrToWav:filename wavSavePath:convertedPath]){
// [session setCategory:AVAudioSessionCategoryPlayback error:nil];
// AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// NSError *err = nil;
// if (canbofang) {
// [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
// }else
// {
// [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
// }
// AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:convertedPath],&shake_sound_male_id);
// AudioServicesAddSystemSoundCompletion(shake_sound_male_id, NULL, NULL, completionCallback, (__bridge void*) self.User_id);
//
// AudioServicesPlaySystemSound(shake_sound_male_id);
//
voicePlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:convertedPath] error:Nil];
[voicePlayer prepareToPlay];
voicePlayer.delegate=self;
// voicePlayer.numberOfLoops =1;
if (canbofang) {
[voicePlayer play];
[_bridge callHandler:@"gameui_play_voice" data:[NSString stringWithFormat:@"%@",self.User_id] ];
}
}else
NSLog(@"amr转wav失败");
responseCallback(@"Response from mediaTypeAudio");
}];
[_bridge registerHandler:@"startshake" handler:^(id data, WVJBResponseCallback responseCallback) {
canshake=YES;
responseCallback(@"startshake from accreditlogin");
}];
[_bridge registerHandler:@"stopshake" handler:^(id data, WVJBResponseCallback responseCallback) {
canshake=NO;
responseCallback(@"startshake from accreditlogin");
}];
[_bridge registerHandler:@"SwitchShake" handler:^(id data, WVJBResponseCallback responseCallback) {
int tempinfo=[data intValue];
if (tempinfo ==1)
{
canvoice=YES;
}else
{
canvoice=NO;
}
responseCallback(@"SwitchShake");
}];
[_bridge registerHandler:@"gamepastetext" handler:^(id data, WVJBResponseCallback responseCallback) {
UIPasteboard * myPasteboard = [UIPasteboard generalPasteboard];
responseCallback(myPasteboard.string);
}];
[_bridge registerHandler:@"gameCopytext" handler:^(id data, WVJBResponseCallback responseCallback) {
UIPasteboard * myPasteboard = [UIPasteboard generalPasteboard];
myPasteboard.string =[NSString stringWithFormat:@"%@",data];
responseCallback(@"gameCopytext");
}];
[_bridge registerHandler:@"OpenurlTitleData" handler:^(id data, WVJBResponseCallback responseCallback) {
NSString *url =[data objectForKey:@"url"];
NSString *title =[data objectForKey:@"title"];
NSString *data_ =[data objectForKey:@"data"];
int orientation=[[data objectForKey:@"orientation"] intValue];
if(first_Time)
{
threeView *detail = [[threeView alloc] initWithNibName:@"threeView" bundle:nil];
[detail Openurl:url Title:title Data:data_ orientation_:orientation];
[FuncPublic PushAnimation:self InsertVC:detail];
first_Time=NO;
}
[self performSelector:@selector(canopen) withObject:nil afterDelay:3.0f];
responseCallback(@"OpenurlTitleData");
}];
[_bridge registerHandler:@"browser" handler:^(id data, WVJBResponseCallback responseCallback) {
NSString *encodeUrl = [data stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",encodeUrl]]];
responseCallback(@"browser");
}];
[_bridge registerHandler:@"startlocation" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"%@",data);
int tempinfo=[data intValue];
if (tempinfo ==1) {
[self.locationManager startUpdatingLocation];
}else
{
[self reGeocodeAction];
}
responseCallback(@"startlocation");
}];
[_bridge registerHandler:@"canclevibrator" handler:^(id data, WVJBResponseCallback responseCallback) {
AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate);
responseCallback(@"canclevibrator");
}];
[_bridge registerHandler:@"vibrator" handler:^(id data, WVJBResponseCallback responseCallback) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
responseCallback(@"vibrator");
}];
[_bridge registerHandler:@"repeatvibrator" handler:^(id data, WVJBResponseCallback responseCallback) {
int tempinfo=[data intValue];
if (tempinfo ==-1) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}else
{
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
responseCallback(@"repeatvibrator");
}];
[_bridge registerHandler:@"voicePlaying" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"%@",data);
int tempinfo=[data intValue];
if (tempinfo ==1) {
canbofang=YES;
}else
{
canbofang=NO;
}
responseCallback(@"voicePlaying");
}];
[_bridge registerHandler:@"friendsSharetypeUrlToptitleDescript" handler:^(id data, WVJBResponseCallback responseCallback) {
NSString *one =[data objectForKey:@"sharefriend"];
NSString *sharetype =[data objectForKey:@"sharetype"];
NSString *two =[data objectForKey:@"type"];NSString *three =[data objectForKey:@"webpageUrl"];
NSString *four =[data objectForKey:@"title"];NSString *five =[data objectForKey:@"description"];
self.UserType=one;
NSLog(@"%@",two);
enum WXScene currentScene;
int friend = [one intValue];
// ======测试分享面板
if(friend ==1){
// 显示分享面板
[SharePanel showWithDictionary:data completion:^(ShareType type, BOOL success) {
// 处理分享结果
}];
}else{
// 使用WechatShareManager处理微信分享
[WechatShareManager shareWithContent:data
completion:^(BOOL success) {
}];
}
return;
if(friend==1)
{
currentScene=WXSceneSession;
}else
{
currentScene=WXSceneTimeline;
}
if ([sharetype intValue]==3&&![XianliaoApiManager isInstallXianliao])
{
[FuncPublic ShowAlert:@"没有安装闲聊应用"];
responseCallback(@"sharefriend");
}
if([two intValue]==1)
{
if ([sharetype intValue]==3) {
XianliaoShareLinkObject *object = [[XianliaoShareLinkObject alloc] init];
object.title = four;
if (five==nil) {
object.linkDescription = four;
}else
object.linkDescription = five;
object.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"sharelogo.png"]);
object.url = three;
[XianliaoApiManager share:object fininshBlock:^(XianliaoShareCallBackType callBackType) {
NSLog(@"callBackType:%ld", (long)callBackType);
[_bridge callHandler:@"sharesuccess" data:@{ @"success":@"2",@"type":[NSString stringWithFormat:@"%d",[self.UserType intValue]]} ];
}];
}else{
[WXApiRequestHandler sendLinkURL:three
TagName:[NSString stringWithFormat:@"%@游戏下载链接",gamehallname]
Title:four
Description:five
ThumbImage:[UIImage imageNamed:@"sharelogo.png"]
InScene:currentScene];
}
}else if([two intValue]==2)
{
if ([sharetype intValue]==3) {
XianliaoShareImageObject *imageObject = [[XianliaoShareImageObject alloc] init];
UIImage *imageName=[FuncPublic getImageWithFullScreenshot];
NSData *dataThumbImage = UIImageJPEGRepresentation(imageName, 0.6);
imageObject.imageData = dataThumbImage;
[XianliaoApiManager share:imageObject fininshBlock:^(XianliaoShareCallBackType callBackType) {
NSLog(@"callBackType:%ld", (long)callBackType);
[_bridge callHandler:@"sharesuccess" data:@{ @"success":@"2",@"type":[NSString stringWithFormat:@"%d",[self.UserType intValue]]} ];
}];
}else{
UIImage *imageName=[FuncPublic getImageWithFullScreenshot];
NSData *dataThumbImage = UIImageJPEGRepresentation(imageName, 0.6);
[WXApiRequestHandler sendImageData:dataThumbImage
TagName:[NSString stringWithFormat:@"%@游戏截图分享",gamehallname]
MessageExt:five
Action:kMessageAction
ThumbImage:[FuncPublic imageByScalingAndCroppingForSize:CGSizeMake(imageName.size.width*0.4, imageName.size.height*0.4) image:imageName]//[UIImage imageNamed:@"sharelogo.png"]
InScene:currentScene];
}
}else
{
if ([sharetype intValue]==3) {
XianliaoShareImageObject *imageObject = [[XianliaoShareImageObject alloc] init];
imageObject.imageUrl = three;
[XianliaoApiManager share:imageObject fininshBlock:^(XianliaoShareCallBackType callBackType) {
NSLog(@"callBackType:%ld", (long)callBackType);
[_bridge callHandler:@"sharesuccess" data:@{ @"success":@"2",@"type":[NSString stringWithFormat:@"%d",[self.UserType intValue]]} ];
}];
}else
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:three]];
UIImage *viewImage = [UIImage imageWithData:data];
[WXApiRequestHandler sendImageData:data
TagName:[NSString stringWithFormat:@"%@公众号二维码分享",gamehallname]
MessageExt:[NSString stringWithFormat:@"%@公众号二维码分享",gamehallname]
Action:kMessageAction
ThumbImage:[FuncPublic imageByScalingAndCroppingForSize:CGSizeMake(viewImage.size.width*0.4, viewImage.size.height*0.4) image:viewImage]
InScene:currentScene];
}
}
responseCallback(@"sharefriend");
}];
[_bridge registerHandler:@"opensaoma" handler:^(id data, WVJBResponseCallback responseCallback) {
responseCallback(@"opensaoma");
}];
[_bridge registerHandler:@"getphoneInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
responseCallback(@"getphoneInfo");
[self getphoneinfo];
}];
[_bridge registerHandler:@"backgameData" handler:^(id data, WVJBResponseCallback responseCallback) {
NSLog(@"backgameData%@",data);
if (backgroundPlayer) {
backgroundPlayer.numberOfLoops = 0;
[backgroundPlayer stop];
backgroundPlayer = nil;
}
[self cleanUpAction];
[WXApiManager sharedManager].delegate = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"backgameDatatwo" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"enterForeground" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"applicationWillResignActive" object:nil];
// [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopradio" object:nil];
[FuncPublic PopAnimation:self];
[[NSNotificationCenter defaultCenter] postNotificationName:@"backgameDatatwo" object:data];
responseCallback(@"backgameData");
}];
[_bridge registerHandler:@"exitRoom" handler:^(id data, WVJBResponseCallback responseCallback) {
[self leaveChannel];
responseCallback(@"exitRoom");
}];
[_bridge registerHandler:@"getVideoinfo" handler:^(id data, WVJBResponseCallback responseCallback) {
@try {
if( ![players containsObject: [data objectForKey:@"playerid"]])
{
[players addObject:[data objectForKey:@"playerid"] ];
responseCallback(@"getVideoinfo");
NSUInteger pmw=[[data objectForKey:@"pmw"] integerValue];
NSUInteger DHeight=self.view.frame.size.height;
NSUInteger pmh=[[data objectForKey:@"pmh"] integerValue];
NSUInteger Dwidth=self.view.frame.size.width;
float fl=(float)Dwidth/pmw;
float f2=(float)DHeight/pmh;
float top =[[data objectForKey:@"top"] floatValue]*f2;
float width =[[data objectForKey:@"width"] floatValue]*fl;
float height =[[data objectForKey:@"height"] floatValue]*f2;
float left =[[data objectForKey:@"left"] floatValue]*fl;
UIView * remoteVideo=[[UIView alloc]initWithFrame:CGRectMake(left, top, width, height)];
remoteVideo.tag=PublicTagTwo+[players count];
[self.view addSubview:remoteVideo];
UIView * remote=[[UIView alloc]initWithFrame:CGRectMake(0,0, remoteVideo.frame.size.width, remoteVideo.frame.size.height)];
remote.tag=PublicTagsix+[players count];
[remoteVideo addSubview:remote];
// remoteVideo.hidden=true;
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(event2:)];
// [remoteVideo addGestureRecognizer:tapGesture];
[tapGesture setNumberOfTapsRequired:1];
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = [[players objectAtIndex:[players count]-1] integerValue];
// Since we are making a simple 1:1 video chat app, for simplicity sake, we are not storing the UIDs. You could use a mechanism such as an array to store the UIDs in a channel.
videoCanvas.view = remote;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupRemoteVideo:videoCanvas];
}
} @catch (NSException *exception) {
NSLog(@"%@",exception);
} @finally {
NSLog(@"@finally");
}
}];
[_bridge registerHandler:@"createRoom" handler:^(id data, WVJBResponseCallback responseCallback) {
responseCallback(@"createRoom");
if(players==nil)
{
players=[[NSMutableArray alloc]init];
}else
{
[players removeAllObjects];
}
if (localVideoBG==nil) {
localVideoBG=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 214, 129)];
[self.view addSubview:localVideoBG];
UIImageView *bg=[[UIImageView alloc]initWithFrame:localVideoBG.frame];
bg.image=[UIImage imageNamed:@"VedioBG.png"];
[localVideoBG addSubview:bg];
//Objective-C //初始化AgoraRtcEngineKit
localVideo=[[UIView alloc]initWithFrame:CGRectMake(12, 10, 136, 109)];
[localVideoBG addSubview:localVideo];
NSString *name = [NSString stringWithFormat:@"VedioB"];
UIButton *btone=[UIButton buttonWithType:UIButtonTypeCustom];
btone.frame=CGRectMake(158, 18, 40, 40);
[btone setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
NSString *selectedName = [NSString stringWithFormat:@"VedioA"];
[btone setBackgroundImage : [UIImage imageNamed: selectedName] forState : UIControlStateSelected];
[localVideoBG addSubview:btone];
// 监听按钮点击
[btone addTarget:self action:@selector(buttonClick:) forControlEvents: UIControlEventTouchDown];
if(1)
{
NSString *name = [NSString stringWithFormat:@"VedioD"];
UIButton *btone=[UIButton buttonWithType:UIButtonTypeCustom];
btone.frame=CGRectMake(158, 68, 40, 40);
[btone setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
NSString *selectedName = [NSString stringWithFormat:@"VedioC"];
[btone setBackgroundImage : [UIImage imageNamed: selectedName] forState : UIControlStateSelected];
[localVideoBG addSubview:btone];
// 监听按钮点击
[btone addTarget:self action:@selector(buttonClickTwo:) forControlEvents: UIControlEventTouchDown];
}
localVideoBG.hidden=YES;
NSUInteger pmw=[[data objectForKey:@"pmw"] integerValue];
NSUInteger DHeight=self.view.frame.size.height;
NSUInteger pmh=[[data objectForKey:@"pmh"] integerValue];
NSUInteger Dwidth=self.view.frame.size.width;
float fl=(float)Dwidth/pmw;
float f2=(float)DHeight/pmh;
float top =[[data objectForKey:@"top"] floatValue]*f2;
float width =[[data objectForKey:@"width"] floatValue]*fl;
float height =[[data objectForKey:@"height"] floatValue]*f2;
float left =[[data objectForKey:@"left"] floatValue]*fl;
remoteVideo1=[[UIView alloc]initWithFrame:CGRectMake(left, top, width, height)];
[self.view addSubview:remoteVideo1];
remote1=[[UIView alloc]initWithFrame:CGRectMake(0,0, remoteVideo1.frame.size.width, remoteVideo1.frame.size.height)];
[remoteVideo1 addSubview:remote1];
// remoteVideo.hidden=true;
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(event1:)];
[remoteVideo1 addGestureRecognizer:tapGesture];
[tapGesture setNumberOfTapsRequired:1];
[self initializeAgoraEngine]; // Tutorial Step 1
[self setupVideo]; // Tutorial Step 2
// [self setupLocalVideo]; // Tutorial Step 3
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
[players addObject:[data objectForKey:@"playerid"] ];
videoCanvas.uid = [[players objectAtIndex:0] integerValue];//[data objectForKey:@"playerid"] ;
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = remote1;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupLocalVideo:videoCanvas];
NSString *roomNumber=[self md5:[NSString stringWithFormat:@"%@%@%@",self.agentinfo,self.gameinfo,[data objectForKey:@"roomid"]]];
[self.agoraKit joinChannelByKey:nil channelName:roomNumber info:nil uid:[[players objectAtIndex:0] integerValue] joinSuccess:^(NSString *channel, NSUInteger uid, NSInteger elapsed) {
// Join channel "demoChannel1"
[self.agoraKit setEnableSpeakerphone:YES];
[UIApplication sharedApplication].idleTimerDisabled = YES;
}];
// [self joinChannel]; // Tutorial Step 4
}
}];
recorderVC = [[ChatVoiceRecorderVC alloc]init];
recorderVC.vrbDelegate = self;
UIImage *back=[UIImage imageNamed:@"Default-568h@2x~iphone.png"];
//远程地址
proimageView=[[UIImageView alloc]initWithImage: [UIImage imageWithCGImage:back.CGImage scale:1 orientation:UIImageOrientationLeft] ];
proimageView.frame=CGRectMake(0,0,DEVW , DEVH);
prolabel.alpha=0;
[self.view addSubview:proimageView];
prolabel=[FuncPublic InstanceLabel:@"拼命启动中..." RECT:CGRectMake(0, 20, 568, 38) RECT5:CGRectMake(0, 20, 568, 38) FontName:@"Arial-BoldMT" Red:52 green:52 blue:52 FontSize:18 Target:self.view Lines:0 TAG:-1 Ailgnment:1];
prolabel.alpha=0;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(YLbackgameData:) name:@"backgameDatatwo" object:nil];
}
-(void)getphoneinfo
{
@try{
CTTelephonyNetworkInfo *telephonyInfo = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = [telephonyInfo subscriberCellularProvider];
NSString *currentCountry=[carrier carrierName];
// NSLog(@"[carrier isoCountryCode]==%@,[carrier allowsVOIP]=%d,[carrier mobileCountryCode=%@,[carrier mobileNetworkCode]=%@",[carrier isoCountryCode],[carrier allowsVOIP],[carrier mobileCountryCode],[carrier mobileNetworkCode]);
UIDevice *device = [[UIDevice alloc] init];
// NSString *name = device.name; //获取设备所有者的名称
NSString *model = device.model; //获取设备的类别
NSString *type = device.localizedModel; //获取本地化版本
//NSString *systemName = device.systemName; //获取当前运行的系统
NSString *systemVersion = device.systemVersion;//获取当前系统的版本
NSString *identifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
ASIdentifierManager *asIM = [[ASIdentifierManager alloc] init];
NSString *idfa = [asIM.advertisingIdentifier UUIDString];
[_bridge callHandler:@"getphoneinfo" data:@{@"PhoneAdresseMAC":identifier,@"PhoneDeviceBrand":model,@"PhoneIMEI":idfa,@"PhoneModel":type,@"PhoneProvidersName":currentCountry,@"PhoneVersion":systemVersion} ];
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
}
-(void)event1:(UITapGestureRecognizer *)gesture
{
return;
if(!remote1.hidden)
{
localVideoBG.hidden=NO;
remote1.hidden=YES;
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = [[players objectAtIndex:0] integerValue];
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = localVideo;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupLocalVideo:videoCanvas];
}else
{
videoCanvas1.view = remoteVideo1;
localVideoBG.hidden=YES;
remote1.hidden=NO;
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = [[players objectAtIndex:0] integerValue];
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = remote1;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupLocalVideo:videoCanvas];
}
}
-(void)event2:(UITapGestureRecognizer *)gesture
{
return;
UIView *remote2=[self.view viewWithTag:gesture.view.tag-PublicTagTwo+PublicTagsix ];
if(!remote2.hidden)
{
localVideoBG.hidden=NO;
remote2.hidden=YES;
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = [[players objectAtIndex:gesture.view.tag-PublicTagTwo] integerValue] ;
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = localVideo;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupRemoteVideo:videoCanvas];
}else
{
videoCanvas1.view = remoteVideo1;
localVideoBG.hidden=YES;
remote2.hidden=NO;
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = [[players objectAtIndex:gesture.view.tag-PublicTagTwo] integerValue];
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = remote2;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupRemoteVideo:videoCanvas];
}
}
- (void)buttonClickTwo:(UIButton *)button
{
if(button.selected)
{
button.selected = NO;
int i= [self.agoraKit muteLocalAudioStream:NO];
NSLog(@"%d",i);
}
else
{
button.selected = YES;
int i= [self.agoraKit muteLocalAudioStream:NO];
NSLog(@"%d",i);
}
}
- (void)buttonClick:(UIButton *)button
{
if(button.selected)
{
button.selected = NO;
int i= [self.agoraKit muteLocalVideoStream:NO];
NSLog(@"%d",i);
localVideo.hidden=NO;
}
else
{
button.selected = YES;
int i= [self.agoraKit muteLocalVideoStream:YES];
NSLog(@"%d",i);
localVideo.hidden=YES;
}
}
- (void)leaveChannel {
if(self.agoraKit!=nil)
[self.agoraKit leaveChannel:^(AgoraRtcStats *stat) {
// [self hideControlButtons]; // Tutorial Step 8
[UIApplication sharedApplication].idleTimerDisabled = NO;
if(localVideoBG!=nil)
{
[localVideoBG removeFromSuperview];
localVideoBG=nil;
}
// [localVideo removeFromSuperview];
self.agoraKit = nil;
if(remoteVideo1!=nil)
{
[remoteVideo1 removeFromSuperview];
remoteVideo1=nil;
[remote1 removeFromSuperview];
remote1=nil;
}
for(int i=0;i<5;i++)
{
UIView *remoteView=[self.view viewWithTag:PublicTagTwo+i+1 ];
if(remoteView!=nil)
{
[remoteView removeFromSuperview];
remoteView=nil;
}
}
}];
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didOfflineOfUid:(NSUInteger)uid reason:(AgoraRtcUserOfflineReason)reason
{
int number=[self isContain:uid];
UIView *remoteVideo=[self.view viewWithTag:PublicTagTwo+number+1];
[players removeObjectAtIndex:number];
if(remoteVideo!=nil)
{
// UIView *remote=[self.view viewWithTag:PublicTagsix+[self isContain:uid]+1] ;
// [remote removeFromSuperview];
[remoteVideo removeFromSuperview];
}
}
-(int)isContain:(NSInteger)f
{
for (int i=0; i<[players count];i++) {
if(f==[[players objectAtIndex:i]integerValue])
return i;
}
return 1;
}
-(void)rtcEngine:(AgoraRtcEngineKit *)engine didVideoMuted:(BOOL)muted byUid:(NSUInteger)uid
{
NSLog(@"didVideoMuted%ld",uid);
// self.remoteVideoMutedIndicator.hidden = !muted;
}
- (void)rtcEngine:(AgoraRtcEngineKit *)engine didVideoEnabled:(BOOL)enabled byUid:(NSUInteger)uid
{
NSLog(@"didVideoEnabled%ld",uid);
}
-(NSString*) md5:( NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), result );
NSString* tmp = [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]
];
tmp = [tmp lowercaseString];
return tmp;
}
// Tutorial Step 1
- (void)initializeAgoraEngine {
self.agoraKit = [AgoraRtcEngineKit sharedEngineWithAppId:appID delegate:self];
}
// Tutorial Step 2
- (void)setupVideo {
[self.agoraKit enableVideo];
// Default mode is disableVideo
[self.agoraKit setVideoProfile:AgoraRtc_VideoProfile_360P swapWidthAndHeight: false];
// Default video profile is 360P
}
// Tutorial Step 3
- (void)setupLocalVideo {
AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
videoCanvas.uid = 20007;
// UID = 0 means we let Agora pick a UID for us
videoCanvas.view = localVideo;
videoCanvas.renderMode = AgoraRtc_Render_Hidden;
[self.agoraKit setupLocalVideo:videoCanvas];
// Bind local video stream to view
}
// Tutorial Step 4
- (void)joinChannel {
[self.agoraKit joinChannelByKey:nil channelName:@"demoChannel1" info:nil uid:20007 joinSuccess:^(NSString *channel, NSUInteger uid, NSInteger elapsed) {
// Join channel "demoChannel1"
[self.agoraKit setEnableSpeakerphone:YES];
[UIApplication sharedApplication].idleTimerDisabled = YES;
}];
// The UID database is maintained by your app to track which users joined which channels. If not assigned (or set to 0), the SDK will allocate one and returns it in joinSuccessBlock callback. The App needs to record and maintain the returned value as the SDK does not maintain it.
}
// Tutorial Step 5
- (void)rtcEngine:(AgoraRtcEngineKit *)engine firstRemoteVideoDecodedOfUid:(NSUInteger)uid size: (CGSize)size elapsed:(NSInteger)elapsed {
// AgoraRtcVideoCanvas *videoCanvas = [[AgoraRtcVideoCanvas alloc] init];
// videoCanvas.uid = uid;
// // Since we are making a simple 1:1 video chat app, for simplicity sake, we are not storing the UIDs. You could use a mechanism such as an array to store the UIDs in a channel.
// videoCanvas.view = remoteVideo1;
// videoCanvas.renderMode = AgoraRtc_Render_Adaptive;
// [self.agoraKit setupRemoteVideo:videoCanvas];
// // Bind remote video stream to view
[_bridge callHandler:@"getVideoinfo" data:[NSString stringWithFormat:@"%ld",uid] ];
}
-(void)canopen
{
first_Time=YES;
}
-(void)commoninit
{
self.callCenter = [[CTCallCenter alloc] init];
self.callWasStarted = NO;
__typeof__(self) weakSelf = self;
[self.callCenter setCallEventHandler:^(CTCall *call) {
if ([[call callState] isEqual:CTCallStateIncoming] ||
[[call callState] isEqual:CTCallStateDialing]) {
if (weakSelf.callWasStarted == NO) {
weakSelf.callWasStarted = YES;
NSLog(@"Call was started.");
// if ([[NSThread currentThread] isMainThread]) {
[backgroundPlayer pause];
[_bridge callHandler:@"phonestate" data:[NSString stringWithFormat:@"2"] ];
//}
}
} else if ([[call callState] isEqual:CTCallStateDisconnected]) {
if (weakSelf.callWasStarted == YES)
{
weakSelf.callWasStarted = NO;
//if ([[NSThread currentThread] isMainThread]) {
[backgroundPlayer play];
NSLog(@"Call was ended.");
[_bridge callHandler:@"phonestate" data:[NSString stringWithFormat:@"0"]];
//}
}
}
}];
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceBatteryLevelDidChangeNotification
object:nil queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *notification) {
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
[self changebattery];
CGFloat level=[UIDevice currentDevice].batteryLevel;
NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel);
[_bridge callHandler:@"getBattery" data:[NSString stringWithFormat:@"%.2f",level] ];
}
}];
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//要监控网络连接状态必须要先调用单例的startMonitoring方法
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//status:
//AFNetworkReachabilityStatusUnknown = -1, 未知
//AFNetworkReachabilityStatusNotReachable = 0, 未连接
//AFNetworkReachabilityStatusReachableViaWWAN = 1, 3G
//AFNetworkReachabilityStatusReachableViaWiFi = 2, 无线连接
// NSLog(@"%d", status);
if(status==AFNetworkReachabilityStatusNotReachable)
{
self.netstate=1;
}else if(status==AFNetworkReachabilityStatusReachableViaWiFi)
{
self.netstate=2;
}else if(status==AFNetworkReachabilityStatusReachableViaWWAN)
{
self.netstate=3;
}
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
[self changenetstate];
[_bridge callHandler:@"getnetwork" data:[NSString stringWithFormat:@"%d",self.netstate]];
}
}];
[manager startMonitoring];
[self changenetstate];
[self changebattery];
}
-(void)changebattery
{
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/app_battery.js",self.gamefilepath,self.game_name] PathType:2];
CGFloat batterylevel = [UIDevice currentDevice].batteryLevel;
NSString *info=[NSString stringWithFormat:@"var app_getbattery=%lf;",batterylevel];
NSData *txtData=[info dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager]createFileAtPath:filePath contents:txtData attributes:nil];
}
-(void)changenetstate
{
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/app_network.js",self.gamefilepath,self.game_name] PathType:2];
NSString *info=[NSString stringWithFormat:@"var app_getnetwork=%d;",self.netstate];
NSData *txtData=[info dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager]createFileAtPath:filePath contents:txtData attributes:nil];
}
-(void)showmessage_
{
[FuncPublic ShowAlert:self.showmessage title:[NSString stringWithFormat:@"%@提醒",gamehallname] viewController:self];
}
-(void)viewWillDisappear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"enterForeground" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"applicationWillResignActive" object:nil];
// [[NSNotificationCenter defaultCenter] removeObserver:self name:@"stopradio" object:nil];
}
-(void)viewWillAppear:(BOOL)animated
{
[FuncPublic SharedFuncPublic]._CurrentShow=2;
[self.navigationController setNavigationBarHidden:YES animated:NO];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground) name:@"enterForeground" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:@"applicationWillResignActive" object:nil];
// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopradio:) name:@"stopradio" object:nil];
if(firsttime)
{
[WXApiManager sharedManager].delegate = self;
firsttime=false;
[self commoninit];
[self configLocationManager];
[self initCompleteBlock];
}else
{
return;
}
NSLog(@"%@",self.agentlist);
if(1)
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@",self.gamefilepath] PathType:2];
if (![fileManager fileExistsAtPath:filePath]) {
[self uplevel:YES];
return;
}
}
NSString * path=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/version.xml",self.gamefilepath,self.game_name] PathType:2];
NSData *dataversion = [[NSData alloc] initWithContentsOfFile:path];
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:dataversion options:0 error:nil];
NSArray *arraythree = [doc nodesForXPath:@"/game/version" error:nil];
GDataXMLElement *elementthree = [arraythree firstObject];
self.versioninfo=[elementthree attributeForName:@"value"].stringValue;
[self uplevel:NO];
}
#pragma mark - alertview delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == PublicTagfive)
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:versionURL]];
}
}
/*
notification方法
*/
//static SystemSoundID shake_sound_male_id = 0;
//static void completionCallback (SystemSoundID mySSID, void* data) {
// // AudioServicesRemoveSystemSoundCompletion (mySSID);
//
// @try{
// NSString *str=(__bridge NSString *)data;
// [[NSNotificationCenter defaultCenter] postNotificationName:@"stopradio" object:str];
// AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
// } @catch (NSException * e) {
// NSLog(@"Exception: %@", e);
// }
//}
//-(void)stopradio:(NSNotification*)notification
//{
// NSNumber *viewNumber = [notification object];;
// [_bridge callHandler:@"gameui_stop_voice" data:[NSString stringWithFormat:@"%@",viewNumber.description]];
//}
-(void)stopradio
{
[_bridge callHandler:@"gameui_stop_voice" data:[NSString stringWithFormat:@"%@",self.User_id]];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
//播放结束时执行的动作
[self stopradio];
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{
//解码错误执行的动作
[self stopradio];
}
- (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{
//处理中断的代码
[self stopradio];
}
- (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{
//处理中断结束的代码 }
[self stopradio];
}
-(void)YLbackgameData:(NSNotification*)notification
{
//if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
NSString *data = [notification object];
//[FuncPublic ShowAlert:@"调用getWebdata"];
[_bridge callHandler:@"getWebdata" data:data ];
// }
}
-(void)enterForeground
{
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
[_bridge callHandler:@"appservice" data:[NSString stringWithFormat:@"2"] ];
} else {
NSLog(@"not main");
}
}
-(void)applicationWillResignActive
{
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
[_bridge callHandler:@"appservice" data:[NSString stringWithFormat:@"1"] ];
} else {
NSLog(@"not main");
}
}
/* 下载更新*/
-(void)downFileFromServer:(NSString *)downstring
{
UIImage *back=[UIImage imageNamed:@"Default-568h@2x~iphone.png"];
//远程地址
background=[[UIImageView alloc]initWithImage: [UIImage imageWithCGImage:back.CGImage scale:1 orientation:UIImageOrientationLeft] ];
background.frame=CGRectMake(0,0,DEVW , DEVH);
[self.view addSubview:background];
pro_Download=[[UIProgressView alloc] initWithFrame:CGRectMake(100,DEVH-100, DEVW-200, 20)];
[pro_Download setProgress:0.0];
[background addSubview:pro_Download];
NSURL *downloadUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",downstring,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]]];
self.downLoadfile=[NSString stringWithFormat:@"%@.zip",self.gamefilepath];
ASIHTTPRequest * requestDownload = [ASIHTTPRequest requestWithURL:downloadUrl];
[requestDownload setDelegate:self];
requestDownload.username=[NSString stringWithFormat:@"download%@",@"test"];
//设置下载路径
[requestDownload setDownloadDestinationPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",self.downLoadfile] PathType:2]];
//设置缓存路径
[requestDownload setTemporaryFileDownloadPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"caches/%@.tmp",self.downLoadfile] PathType:2]];
//设置支持断点续传
[requestDownload setAllowResumeForFileDownloads:YES];
//设置跟踪进度条
[requestDownload setDownloadProgressDelegate:pro_Download];
[requestDownload setDidFinishSelector:@selector(requestFinished:)];
[requestDownload setDidFailSelector:@selector(requestFailed:)];
[requestDownload start];
}
// 监听到了属性改变会调用这个方法
- (void)requestStarted:(ASIHTTPRequest *)request
{
NSLog(@"start");
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSLog(@"finished");
[NSThread detachNewThreadSelector:@selector(unzip) toTarget:self withObject:nil];
}
- (void)unzip
{
NSString *zipPath = [FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",self.downLoadfile] PathType:2];
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@",self.gamefilepath] PathType:2];
ZipArchive *zip = [[ZipArchive alloc] init];
if ([zip UnzipOpenFile:zipPath])
{
if ([zip UnzipFileTo: filePath overWrite:YES])
{
//此处为空
}
}
[zip UnzipCloseFile];
[self unzipDone];
}
- (void)unzipDone
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager removeItemAtPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",self.downLoadfile] PathType:2] error:nil];
[background removeFromSuperview];
[self initView];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(@"Error %@", [request error]);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
NSLog(@"lskdjfl= %f",pro.fractionCompleted);
}
-(void)uplevel:(int )gamevers download:(NSString *)downstring
{
if (gamevers>[self.versioninfo intValue]) {
self.gamefilepath=[NSString stringWithFormat:@"%@1",self.gamefilepath];
[FuncPublic SaveDefaultInfo:self.gamefilepath Key:[NSString stringWithFormat:@"%@",self.game_name]];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *booksDir=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@",self.gamefilepath] PathType:2];
[fileManager createDirectoryAtPath:booksDir withIntermediateDirectories:YES attributes:nil error:nil];
[self downFileFromServer:downstring];
return;
}else
{
[self initView];
return;
}
}
- (BOOL)isEmptyString:(NSString *) string {
if([string length] == 0) { //string isempty or nil
return YES;
}
else if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]length] == 0) {
//string is all whitespace
return YES;
}
return NO;
}
//-(NSDictionary *)gonetconfig: (NSString *)weburl
//{
//
//
// NSString *url_=[NSString stringWithFormat:@"%@%@",weburl,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]];
// NSURL *urlPath = [NSURL URLWithString:url_];
//
// NSData *requestData = [NSData dataWithContentsOfURL:urlPath];
//
// if(requestData==nil)
// {
// return nil;
// }
// //[timer invalidate];
// // [timertwo invalidate];
// NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
// NSString* str = [[NSString alloc]initWithFormat:@"%@",[result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
// if(str.length<=100)
// {
// [FuncPublic ShowAlert:str title:[NSString stringWithFormat:@"%@提醒",gamehallname] viewController:self];
// return nil;
// }
//
// NSDictionary * obj_return = [str JSONValue];
//
// NSDictionary *obj=[FuncPublic dictionaryWithJsonString:str];//字符串转数组
//
//
//
// // NSDictionary *data=[obj_return objectForKey:@"agentlist"];
// //self.agentlist=[obj_return objectForKey:@"agentlist"];
//
// // self.gamelist=[obj_return objectForKey:@"gamelist"];
//
// if (![self isEmptyString:[obj_return objectForKey:@"showmessage"]]) {
// self.showmessage=[obj_return objectForKey:@"showmessage"];
//
// }
// return obj_return;
//}
-(void)gonetconfig: (NSString *)weburl
{
NSDictionary * obj_return;
@try {
NSString *url_=[NSString stringWithFormat:@"%@%@",weburl,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]];
NSURL *urlPath = [NSURL URLWithString:url_];
NSData *requestData = [NSData dataWithContentsOfURL:urlPath];
if(requestData==nil)
{
return;
}
NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithFormat:@"%@",[result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
if(str.length<=100)
{
[FuncPublic ShowAlert:str title:[NSString stringWithFormat:@"%@提醒",gamehallname] viewController:self];
return;
}
obj_return = [str JSONValue];
self.magentlist=obj_return;
if (![self isEmptyString:[obj_return objectForKey:@"showmessage"]]) {
self.showmessage=[obj_return objectForKey:@"showmessage"];
}
} @catch (NSException *exception) {
[FuncPublic ShowAlert:@"转json失败请检查格式 "];
}
}
-(void)gonetconfig1: (NSDictionary *)agentlist{
self.magentlist = agentlist;
}
-(void)gonetconfigone1: (NSDictionary *)gametlist isfirt:(BOOL )isfirt{
self.mgamelist = gametlist;
if (![self isEmptyString:[gametlist objectForKey:@"showmessage"]]) {
self.showmessage=[gametlist objectForKey:@"showmessage"];
}
[self chulishengji:isfirt];
}
-(void)gonetconfigone: (NSString *)weburl isfirt:(BOOL )isfirt
{
NSDictionary * obj_return;
@try {
NSString *url_=[NSString stringWithFormat:@"%@%@",weburl,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]];
NSURL *urlPath = [NSURL URLWithString:url_];
NSData *requestData = [NSData dataWithContentsOfURL:urlPath];
if(requestData==nil)
{
return;
}
NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithFormat:@"%@",[result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
if(str.length<=100)
{
[FuncPublic ShowAlert:str title:[NSString stringWithFormat:@"%@提醒",gamehallname] viewController:self];
return;
}
obj_return = [str JSONValue];
if(obj_return!=nil)
{
self.mgamelist=obj_return;
}
if (![self isEmptyString:[obj_return objectForKey:@"showmessage"]]) {
self.showmessage=[obj_return objectForKey:@"showmessage"];
}
} @catch (NSException *exception) {
[FuncPublic ShowAlert:@"转json失败请检查格式 "];
}
[self chulishengji:isfirt];
}
-(void)chulishengji:(BOOL )isfirt{
NSDictionary *magentdata,*mgamedata1;
if(self.magentlist!=nil&&self.mgamelist!=nil)
{
magentdata=self.magentlist;
mgamedata1=self.mgamelist;
}else{
[FuncPublic ShowAlert:@"self.mgamelist为空" ];
}
// [FuncPublic ShowAlert:@"处理升级"];
//&&gamedata!=nil
if(magentdata!=nil&&mgamedata1!=nil){
// [FuncPublic ShowAlert:@"正在处理game升级"];
versionConfig *agentconfig=[self getagentversion:magentdata];
versionConfig *gameconfig= [self getgameversion:mgamedata1];
// [FuncPublic ShowAlert: [NSString stringWithFormat:@"gamegameversion=%@;gamegamedownload=%@",gameconfig.game_version,gameconfig.game_download] title:@"error info!" viewController:self];
// [FuncPublic ShowAlert: [NSString stringWithFormat:@"agentgameversion=%@;agentgamedownload=%@",agentconfig.game_version,agentconfig.game_download] title:@"error info!" viewController:self];
//
NSString *game_version=nil;
NSString *game_download=nil;
//处理game升级
if([FuncPublic isBlankString:agentconfig.game_download]==NO &&[FuncPublic isBlankString:gameconfig.game_download]==NO){
@try
{
game_download=gameconfig.game_download;
game_version=gameconfig.game_version;
if([agentconfig.game_version intValue]>[gameconfig.game_version intValue]){
game_download=agentconfig.game_download;
game_version=agentconfig.game_version;
}
}
@catch (NSException *exception)
{
}
}else{
@try {
if([FuncPublic isBlankString:agentconfig.game_download]==NO){
game_download=agentconfig.game_download;
game_version=agentconfig.game_version;
}
if([FuncPublic isBlankString:gameconfig.game_download]==NO){
game_download=gameconfig.game_download;
game_version=gameconfig.game_version;
}
} @catch (NSException *exception) {
}
}
self.game_version_=game_version;
self.game_zip_=game_download;
if(self.showmessage!=nil)
{
if(![self.showmessage isEqualToString:@""])
{
[self showmessage_];
return;
}
}
if (isfirt) {
[self downFileFromServer:self.game_zip_];
return;
}else{
[self uplevel:[self.game_version_ intValue] download:self.game_zip_];
return;
}
}
}
-(void)uplevel:(BOOL )isfirt
{
if(self.gameinfo!=nil)
{
if(self.agentinfo!=nil&&self.gameinfo!=nil ){
NSDictionary *agentdata=nil;
NSDictionary *gamedata=nil;
// NSString *Sagentlist=[NSString stringWithFormat:@"agentid=%@",self.agentlist];
for (int x=0; x<[self.agentlist count]; x++) {
NSDictionary *infoagent=[self.agentlist objectAtIndex:x];
if([[infoagent objectForKey:@"agentid"] isEqualToString:self.agentinfo]){
if (![self isEmptyString:[infoagent objectForKey:@"showmessage"]]) {
self.showmessage=[infoagent objectForKey:@"showmessage"];
}
[self gonetconfig1:infoagent];
// NSString *url=[infoagent objectForKey:@"url"];
//
// if(![self isEmptyString:url]){
// // [FuncPublic ShowAlert:@"代理ID匹配" ];
// [self gonetconfig1:infoagent];
//// [self gonetconfig:url];
//
// }else{
// [FuncPublic ShowAlert:@"agent url 地址为空" ];
//
// }
break;
}
}
for (int x=0; x<[self.gamelist count]; x++) {
NSDictionary *infogame=[self.gamelist objectAtIndex:x];
if([[infogame objectForKey:@"gameid"] isEqualToString:self.gameinfo]){
if (![self isEmptyString:[infogame objectForKey:@"showmessage"]]) {
self.showmessage=[infogame objectForKey:@"showmessage"];
}
[self gonetconfigone1:infogame isfirt:isfirt];
// NSString *url=[infogame objectForKey:@"url"];
//
// if(![self isEmptyString:url]){
//
// // [FuncPublic ShowAlert:@"gameID匹配" ];
// [self gonetconfigone1:infogame isfirt:isfirt];
//// [self gonetconfigone:url isfirt:isfirt];
//
// }else{
// [FuncPublic ShowAlert:@"game url 地址为空" ];
//
// }
break;
}
}
}
}else{
for (int x=0; x<[self.agentlist count]; x++) {
NSDictionary *infoagent=[self.agentlist objectAtIndex:x];
if([[infoagent objectForKey:@"agentid"] isEqualToString:self.agentinfo])
{
// NSString * one=[infoagent objectForKey:@"showmessage"];
if (![self isEmptyString:[infoagent objectForKey:@"showmessage"]]) {
self.showmessage=[infoagent objectForKey:@"showmessage"];
}
NSArray *gamelist=[infoagent objectForKey:@"gamelist"];
for (int i=0; i<[gamelist count]; i++) {
NSDictionary *info=[gamelist objectAtIndex:i];
if([[info objectForKey:@"gameid"] isEqualToString:self.gameinfo])
{
self.openweb=[info objectForKey:@"openweb"];
if (![self isEmptyString:[info objectForKey:@"showmessage"]]) {
self.showmessage=[info objectForKey:@"showmessage"];
}
NSString *game_version=[info objectForKey:@"game_version"];
NSString *game_zip=[info objectForKey:@"game_zip"];
if (![game_zip isEqualToString:@""]) {
self.game_zip_=[info objectForKey:@"game_zip"];
}
if ([game_version integerValue]!=0) {
self.game_version_=[info objectForKey:@"game_version"];
}
NSArray *channellist=[info objectForKey:@"channellist"];
for (int j=0; j<[channellist count]; j++) {
NSDictionary *infotwo=[channellist objectAtIndex:j];
if([[infotwo objectForKey:@"channelid"] isEqualToString:self.channel_id])
{
if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) {
self.showmessage=[infotwo objectForKey:@"showmessage"];
}
game_version=[infotwo objectForKey:@"game_version"];
game_zip=[infotwo objectForKey:@"game_zip"];
if (![game_zip isEqualToString:@""]) {
self.game_zip_=[infotwo objectForKey:@"game_zip"];
}
if ([game_version integerValue]!=0) {
self.game_version_=[infotwo objectForKey:@"game_version"];
}
NSArray *marketlist=[infotwo objectForKey:@"marketlist"];
for (int x=0; x<[marketlist count]; x++) {
NSDictionary *infothree=[marketlist objectAtIndex:x];
if([[infothree objectForKey:@"marketid"] intValue]==[self.market intValue])
{
if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) {
self.showmessage=[infothree objectForKey:@"showmessage"];
}
game_version=[infothree objectForKey:@"game_version"];
game_zip=[infothree objectForKey:@"game_zip"];
if (![game_zip isEqualToString:@""]) {
self.game_zip_=[infothree objectForKey:@"game_zip"];
}
if ([game_version integerValue]!=0) {
self.game_version_=[infothree objectForKey:@"game_version"];
}
if(self.showmessage!=nil)
{
if(![self.showmessage isEqualToString:@""])
{
[self showmessage_];
return;
}
}
if (isfirt) {
[self downFileFromServer:self.game_zip_];
return;
}else{
[self uplevel:[self.game_version_ intValue] download:self.game_zip_];
return;
}
}
}
}
}
}
}
}
}
if(self.showmessage!=nil)
{
if(![self.showmessage isEqualToString:@""])
{
[self showmessage_];
return;
}
}
}
// [FuncPublic ShowAlert: [NSString stringWithFormat:@"agentid=%@;gameid=%@;channelid=%@;game_version_server=%@;marketid=%@;game_version=%@;game_zip=%@",self.agentinfo,self.gameinfo,self.channel_id,self.game_version_,self.market, self.versioninfo,self.game_zip_] title:@"error info!" viewController:self];
}
-(versionConfig *) getagentversion :(NSDictionary *)agentdata{
versionConfig *versonfig=[versionConfig new];
NSString *game_version;
NSString *game_zip;
NSString *agentid=[agentdata objectForKey:@"agentid"];
if([FuncPublic isBlankString:agentid]==NO){
if([agentid isEqualToString:self.agentinfo]){
if (![self isEmptyString:[agentdata objectForKey:@"showmessage"]]) {
self.showmessage=[agentdata objectForKey:@"showmessage"];
}
// [FuncPublic ShowAlert:self.agentinfo];
NSArray *channellist=[agentdata objectForKey:@"channellist"];
if(channellist!=nil){
for (int j=0; j<[channellist count]; j++) {
NSDictionary *infotwo=[channellist objectAtIndex:j];
if([FuncPublic isBlankString:[infotwo objectForKey:@"channelid"]]==NO){
if([[infotwo objectForKey:@"channelid"] isEqualToString:self.channel_id]){
// [FuncPublic ShowAlert:self.channel_id];
if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) {
self.showmessage=[infotwo objectForKey:@"showmessage"];
}
NSArray *marketlist=[infotwo objectForKey:@"marketlist"];
if(marketlist!=nil)
{
for (int x=0; x<[marketlist count]; x++) {
NSDictionary *infothree=[marketlist objectAtIndex:x];
// [NSString stringWithFormat:@"%@", [info objectForKey:@"game_version"]]
NSString *marketid = [NSString stringWithFormat:@"%@", [infothree objectForKey:@"marketid"]];
if([FuncPublic isBlankString:marketid]==NO){
if([marketid isEqualToString: self.market])
{
// [FuncPublic ShowAlert:self.market];
if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) {
self.showmessage=[infothree objectForKey:@"showmessage"];
}
NSArray *gamelist=[infothree objectForKey:@"gamelist"];
if(gamelist!=nil)
{
for (int i=0; i<[gamelist count]; i++) {
NSDictionary *info=[gamelist objectAtIndex:i];
if([FuncPublic isBlankString:[info objectForKey:@"gameid"]]==NO){
if([[info objectForKey:@"gameid"] isEqualToString:self.gameinfo]){
// [FuncPublic ShowAlert:self.gameinfo];
if (![self isEmptyString:[info objectForKey:@"showmessage"]]) {
self.showmessage=[info objectForKey:@"showmessage"];
}
game_version=[NSString stringWithFormat:@"%@", [info objectForKey:@"game_version"]];
game_zip=[info objectForKey:@"game_download"];
if ([FuncPublic isBlankString:game_zip]==NO) {
versonfig.game_download=game_zip;
}
if ([game_version integerValue]!=0) {
versonfig.game_version=game_version;
}
}
}
}
}
}
}
}
}
}
}
}
}
}else{
}
}
return versonfig;
}
-(versionConfig *) getgameversion :(NSDictionary *)gamedata{
versionConfig *versonfig=[versionConfig new];
NSString *game_version;
NSString *game_zip;
NSString *gameid=[gamedata objectForKey:@"gameid"];
if([FuncPublic isBlankString:gameid]==NO){
if([gameid isEqualToString:self.gameinfo]){
if (![self isEmptyString:[gamedata objectForKey:@"showmessage"]]) {
self.showmessage=[gamedata objectForKey:@"showmessage"];
}
game_version=[NSString stringWithFormat:@"%@", [gamedata objectForKey:@"game_version"]];
game_zip=[gamedata objectForKey:@"game_zip"];
if ([FuncPublic isBlankString:game_zip]==NO) {
versonfig.game_download=game_zip;
}
if ([game_version integerValue]!=0) {
versonfig.game_version=game_version;
}
// NSArray *agentlist=[gamedata objectForKey:@"agentlist"];
//
// if(agentlist!=nil){
// for (int j=0; j<[agentlist count]; j++) {
// NSDictionary *infotwo=[gamedata objectForKey:@"agentlist"];
// if([FuncPublic isBlankString:[infotwo objectForKey:@"agentid"]]==NO){
//
// if([[infotwo objectForKey:@"agentid"] isEqualToString:self.agentinfo]){
// NSDictionary *infotwo=gamedata;
// if (![self isEmptyString:[infotwo objectForKey:@"showmessage"]]) {
// self.showmessage=[infotwo objectForKey:@"showmessage"];
// }
//
//
//
// game_version=[infotwo objectForKey:@"game_version"];
// game_zip=[infotwo objectForKey:@"game_zip"];
//
// if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip;
//
// }
// if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version;
//
// }
//
//
// NSArray *channellist=[infotwo objectForKey:@"channellist"];
// if(channellist!=nil){
// for (int x=0; x<[channellist count]; x++) {
// NSDictionary *infothree=[channellist objectAtIndex:x];
//
// if([FuncPublic isBlankString:[infothree objectForKey:@"channelid"]]==NO){
// if([[infothree objectForKey:@"channelid"] isEqualToString: self.channel_id])
// {
//
//
// if (![self isEmptyString:[infothree objectForKey:@"showmessage"]]) {
// self.showmessage=[infothree objectForKey:@"showmessage"];
// }
// game_version=[infothree objectForKey:@"game_version"];
// game_zip=[infothree objectForKey:@"game_zip"];
// if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip;
//
// }
// if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version;
//
// }
//
//
//
//
// NSArray *marketlist=[infothree objectForKey:@"marketlist"];
// if(marketlist!=nil){
// for (int i=0; i<[marketlist count]; i++) {
// NSDictionary *info=[marketlist objectAtIndex:i];
// if([FuncPublic isBlankString:[info objectForKey:@"marketid"]]==NO){
// if([[info objectForKey:@"marketid"] isEqualToString:self.market]){
//
// if (![self isEmptyString:[info objectForKey:@"showmessage"]]) {
// self.showmessage=[info objectForKey:@"showmessage"];
// }
//
//
// game_version=[info objectForKey:@"game_version"];
// game_zip=[info objectForKey:@"game_zip"];
// if ([FuncPublic isBlankString:game_zip]==NO) {
// versonfig.game_download=game_zip;
//
// }
// if ([game_version integerValue]!=0) {
// versonfig.game_version=game_version;
//
// }
//
//
//
// }
// }
//
// }
// }
//
//
// }
// }
//
//
// }
//// }
////
//// }
////
////
//// }
//// }
//
//
// }
}else{
}
}
return versonfig;
}
-(void)initJSdata
{
NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/app_data.js",self.gamefilepath,self.game_name] PathType:2];
NSString *info=[NSString stringWithFormat:@"var app_version=1;var app_gameconfig='%@';var app_gamedir='%@';var app_gamestart='%@';var app_agent='%@';var app_appversion='%d';var app_market='%@';var app_channel='%@';var app_Launchtype=1;var app_getwifisignalLevel=1;var app_gamename='%@';var app_invitationcode='%@';",self.gameconfig, self.gamefilepath,self.game_name,self.agentinfo,self.result_state,self.market,self.channel_id,self.game_name,self.tuiguang_id];
NSData *txtData=[info dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager]createFileAtPath:filePath contents:txtData attributes:nil];
}
-(void)initinfo:(NSString *)gamename downurl:(NSString *)url gamedata:(NSString *)data agent:(NSString *)agent_info channel:(NSString *)channelinfo market:(NSString *)marketid gamedir:(NSString *)gamedir_ agentlist:(NSArray *)agentlist_ gamelist:(NSArray *)gamelist_ result:(int)result;
{
self.result_state=result;
self.market=marketid;
self.agentlist=agentlist_;
self.gamelist=gamelist_;
self.game_name=gamename;
self.gameinfo=url;
self.dataofgame=data;
//self.gamefilepath=gamename;
self.agentinfo=agent_info;
self.channel_id=channelinfo;
NSString *filepath=[FuncPublic GetDefaultInfo:[NSString stringWithFormat:@"%@",self.game_name]];
if (filepath!=nil) {
self.gamefilepath=filepath;
}else
{
self.gamefilepath=gamename;
[FuncPublic SaveDefaultInfo:self.gamefilepath Key:[NSString stringWithFormat:@"%@",self.game_name]];
}
}
/* 录音*/
- (void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString*)_fileName{
NSLog(@"录音完成,文件路径:%@ %@",_filePath,_fileName);
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
// 检查文件是否存在
if (![[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
NSLog(@"录音文件不存在: %@", _filePath);
return;
}
// 使用fileURLWithPath而不是URLWithString因为是本地文件路径
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:_filePath] error:&error];
if (error || play == nil) {
NSLog(@"创建AVAudioPlayer时出错: %@", [error localizedDescription]);
return;
}
// 获取音频时长
NSTimeInterval interval = play.duration;
NSInteger time = round(interval);
NSLog(@"录音时长: %ld秒", (long)time);
// 如果录音时长太短小于1秒可能是无效录音
if (interval < 1.0) {
NSLog(@"录音时长过短,可能无效: %.2f秒", interval);
return;
}
//4.播放
if (play == nil)
{
NSLog(@"ERror creating player: %@", [play description]);
}else{
[play play];
}
NSString *amrPath = [FuncPublic GetPathByFileName:_fileName ofType:@"amr"];
NSLog(@"尝试转换WAV到AMR源文件: %@,目标文件: %@", _filePath, amrPath);
// 检查WAV文件格式
NSDictionary *audioFileSettings = nil;
AVAudioFile *audioFile = nil;
@try {
audioFile = [[AVAudioFile alloc] initForReading:[NSURL fileURLWithPath:_filePath] error:&error];
if (!error) {
audioFileSettings = audioFile.processingFormat.settings;
NSLog(@"WAV文件格式: %@", audioFileSettings);
// 检查采样率是否为8000Hz
float sampleRate = [[audioFileSettings objectForKey:AVSampleRateKey] floatValue];
if (sampleRate != 8000.0f) {
NSLog(@"警告: WAV文件采样率不是8000Hz (实际: %.0fHz), 可能影响转换", sampleRate);
// 这里可以尝试重新采样WAV文件但为简单起见先尝试直接转换
}
}
} @catch (NSException *exception) {
NSLog(@"读取WAV文件格式时出错: %@", exception);
}
// 转换WAV到AMR
int result = [VoiceConverter ConvertWavToAmr:_filePath amrSavePath:amrPath];
if (result) {
NSLog(@"转换WAV到AMR成功");
NSData *amrData = [NSData dataWithContentsOfFile:amrPath];
if (amrData && amrData.length > 0) {
// 数据有效使用QiniuManager上传到七牛云
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *timeStr = [formatter stringFromDate:[NSDate date]];
NSString *uniqueFileName = [NSString stringWithFormat:@"%@_%08X.amr", timeStr, arc4random()];
// 显示上传状态提示
// UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示"
// message:@"正在上传录音文件..."
// preferredStyle:UIAlertControllerStyleAlert];
// [self presentViewController:alertController animated:YES completion:nil];
// 调用七牛云管理器上传文件
[[QiniuManager sharedManager] uploadAudioFile:amrPath
fileName:uniqueFileName
progressHandler:^(float progress) {
// 更新上传进度提示
// dispatch_async(dispatch_get_main_queue(), ^{
// alertController.message = [NSString stringWithFormat:@"正在上传录音文件... %.0f%%", progress * 100];
// });
}
completionHandler:^(NSString *key, NSError *error) {
// 关闭上传进度提示
dispatch_async(dispatch_get_main_queue(), ^{
// [alertController dismissViewControllerAnimated:YES completion:nil];
if (error) {
// 上传失败处理
// UIAlertController *errorAlert = [UIAlertController alertControllerWithTitle:@"上传失败"
// message:error.localizedDescription
// preferredStyle:UIAlertControllerStyleAlert];
// UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
// [errorAlert addAction:okAction];
// [self presentViewController:errorAlert animated:YES completion:nil];
//
NSLog(@"七牛云上传失败: %@", error);
} else {
// 上传成功获取文件URL
NSString *fileUrl = [[QiniuManager sharedManager] getFileUrlWithKey:key];
NSString *audiourl=[NSString stringWithFormat:@"%@%@/%@",@"http://",kQiniuDomain,uniqueFileName];
[_bridge callHandler:@"getaudiourl" data:@{ @"audiourl":audiourl,@"time":[NSString stringWithFormat:@"%ld",(long)time]} ];
NSLog(@"七牛云上传成功文件URL: %@", fileUrl);
// 将录音文件URL传递给JS接口
if (self->_bridge) {
[self->_bridge callHandler:@"recordSuccess" data:@{
@"fileUrl": fileUrl,
@"fileName": uniqueFileName,
@"fileKey": key
}];
}
}
});
}];
// 原有的上传流程代码注释掉或删除
} else {
NSLog(@"AMR文件无效或为空");
}
} else {
NSLog(@"转换WAV到AMR失败");
// 尝试打印WAV文件的基本信息帮助调试
NSData *wavData = [NSData dataWithContentsOfFile:_filePath];
NSLog(@"WAV文件大小: %lu 字节", (unsigned long)wavData.length);
if (wavData && wavData.length >= 44) { // 至少包含WAV文件头
// 提取WAV头信息
const char *bytes = [wavData bytes];
NSString *riffMarker = [[NSString alloc] initWithBytes:bytes length:4 encoding:NSASCIIStringEncoding];
NSString *waveMarker = [[NSString alloc] initWithBytes:(bytes + 8) length:4 encoding:NSASCIIStringEncoding];
UInt16 audioFormat;
[wavData getBytes:&audioFormat range:NSMakeRange(20, 2)];
UInt16 numChannels;
[wavData getBytes:&numChannels range:NSMakeRange(22, 2)];
UInt32 sampleRate;
[wavData getBytes:&sampleRate range:NSMakeRange(24, 4)];
UInt16 bitsPerSample;
[wavData getBytes:&bitsPerSample range:NSMakeRange(34, 2)];
NSLog(@"WAV文件头信息 - RIFF标记: %@, WAVE标记: %@, 格式: %d, 通道数: %d, 采样率: %d, 采样位数: %d",
riffMarker, waveMarker, audioFormat, numChannels, sampleRate, bitsPerSample);
}
}
}
#pragma mark - 微信回调
- (void)managerDidRecvMessageResponse:(SendMessageToWXResp *)response {
if(response.errCode==0)
{
[_bridge callHandler:@"sharesuccess" data:@{ @"success":@"2",@"type":[NSString stringWithFormat:@"%d",[self.UserType intValue]]} ];
}
}
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
if (response.code==nil) {
[FuncPublic ShowAlert:@"授权失败"];
return;
}
//1.创建一个web路径
NSString *urlStr=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?code=%@&secret=%@&appid=%@&grant_type=authorization_code",response.code,Appsecret,kAuthOpenID];
urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];
//通过URL设置网络请求
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSError *error=nil;
//获取服务器数据
NSData *requestData= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
if (error) {
NSLog(@"错误信息:%@",[error localizedDescription]);
[FuncPublic ShowAlert:@"授权失败"];
return;
}
NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
NSLog(@"返回结果:%@",result);
if (result==nil) {
[FuncPublic ShowAlert:@"授权失败"];
return;
}
NSString* stra = [[NSString alloc] initWithData:requestData encoding:NSUTF8StringEncoding]; //转换信息
//去除两边空格
NSString* str = [[NSString alloc]initWithFormat:@"%@",[stra stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSDictionary * obj_return = [str JSONValue];
NSString *access_token=[obj_return objectForKey:@"access_token"];
NSString *openid=[obj_return objectForKey:@"openid"];
NSString *webPath=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
webPath=[webPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *urltwo=[NSURL URLWithString:webPath];
//通过URL设置网络请求
NSURLRequest *requesttwo = [[NSURLRequest alloc]initWithURL:urltwo cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
NSError *errortwo=nil;
//获取服务器数据
NSData *requestDatatwo= [NSURLConnection sendSynchronousRequest:requesttwo returningResponse:nil error:&errortwo];
if (errortwo) {
NSLog(@"错误信息:%@",[errortwo localizedDescription]);
}else{
NSString *resulttwo=[[NSString alloc]initWithData:requestDatatwo encoding:NSUTF8StringEncoding];
NSLog(@"返回结果:%@",resulttwo);
}
NSString* stra_ = [[NSString alloc] initWithData:requestDatatwo encoding:NSUTF8StringEncoding]; //转换信息
//去除两边空格
NSString* str_ = [[NSString alloc]initWithFormat:@"%@",[stra_ stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
NSDictionary * obj_returntwo= [str_ JSONValue];
NSLog(@"obj_do:%@", obj_returntwo);
NSString* nickname=[obj_returntwo objectForKey:@"nickname"];
// NSString* nickname=@"chao'chao";
nickname = [nickname stringByReplacingOccurrencesOfString:@"'" withString:@""];
[_bridge callHandler:@"sharelogin" data:@{ @"openid":[obj_returntwo objectForKey:@"openid"],@"headimgurl":[obj_returntwo objectForKey:@"headimgurl"],@"nickname":nickname ,@"sex":[obj_returntwo objectForKey:@"sex"] ,@"city":[FuncPublic danbian:[obj_returntwo objectForKey:@"city"]] ,@"Province":[FuncPublic danbian:[obj_returntwo objectForKey:@"province"]] ,@"unionid":[obj_returntwo objectForKey:@"unionid"] } ];
}
#pragma mark - 手机震动
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake)
{
if(canshake)
{
[_bridge callHandler:@"shakeEnd" data:nil];
if(canvoice)
{
NSURL *url_=[[NSBundle mainBundle]URLForResource:@"shake_sound_male" withExtension:@"mp3"];
AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil];
[audioPlayer prepareToPlay];
[audioPlayer play];
}
}
}
}
/*
地图定位
*/
- (void)configLocationManager
{
self.locationManager = [[AMapLocationManager alloc] init];
[self.locationManager setDelegate:self];
//设置期望定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
//设置不允许系统暂停定位
[self.locationManager setPausesLocationUpdatesAutomatically:NO];
//设置允许在后台定位
// [self.locationManager setAllowsBackgroundLocationUpdates:YES];
//设置允许连续定位逆地理
[self.locationManager setLocatingWithReGeocode:YES];
//设置定位超时时间
[self.locationManager setLocationTimeout:DefaultLocationTimeout];
//设置逆地理超时时间
[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
}
- (void)cleanUpAction
{
//停止定位
[self.locationManager stopUpdatingLocation];
[self.locationManager setDelegate:nil];
}
- (void)reGeocodeAction
{
//进行单次带逆地理定位请求
[self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)locAction
{
//进行单次定位请求
[self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}
#pragma mark - Initialization
- (void)initCompleteBlock
{
//__weak RootVC *weakSelf = self;
self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
{
if (error)
{
NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//如果为定位失败的error则不进行后续操作
if (error.code == AMapLocationErrorLocateFailed)
{
return;
}
}
//得到定位信息
if (location)
{
if (regeocode)
{
NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]);
if(regeocode.formattedAddress!=nil)
{
@try{
[_bridge callHandler:@"getlocationinfo" data:@{@"address":regeocode.formattedAddress,@"city":regeocode.city,@"cityCode":regeocode.citycode,@"country":regeocode.country,@"district":regeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":regeocode.province,@"street":regeocode.street} ];
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
}
}else
{
NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
}
}
};
}
#pragma mark - AMapLocationManager Delegate
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
}
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
NSLog(@"location:{lat:%f; lon:%f; accuracy:%f; reGeocode:%@}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy, reGeocode.formattedAddress);
if (reGeocode!=nil) {
if(reGeocode.formattedAddress!=nil)
{
@try{
[_bridge callHandler:@"getlocationinfo" data:@{@"address":reGeocode.formattedAddress,@"city":reGeocode.city,@"cityCode":reGeocode.citycode,@"country":reGeocode.country,@"district":reGeocode.district,@"latitude":[NSString stringWithFormat:@"%f",location.coordinate.latitude],@"longitude":[NSString stringWithFormat:@"%f",location.coordinate.longitude],@"province":reGeocode.province,@"street":reGeocode.street} ];
} @catch (NSException * e) {
NSLog(@"Exception: %@", e);
}
}
}}
@end