// RootVC.m // msext // // Created by chao on 15/7/23. // Copyright (c) 2015年 chao. All rights reserved. // #import "RootVC.h" #import "Bridge.h" #import "WXApiManager.h" #import "WXApiRequestHandler.h" #import "NSString+SBJSON.h" #import "SBJSON.h" #import #import #import #import #import #import #import #import "AFNetworking.h" #import "GDataXMLNode.h" #import "ASIHTTPRequest.h" #import "ZipArchive.h" #import "threeView.h" #import #import "VoiceConverter.h" #import "ChatVoiceRecorderVC.h" #import "fourviewVC.h" #import #import #import "Reachability.h" #define DefaultLocationTimeout 10 #define DefaultReGeocodeTimeout 5 @interface RootVC () { UIWebView *_webView; NSString *versionURL; AVAudioPlayer *backgroundPlayer; SystemSoundID sound; ChatVoiceRecorderVC *recorderVC; // NSString *videoInfo[]; NSURLSessionDownloadTask *_downloadTask; UIImageView *imageView; UIImageView *proimageView; UILabel *prolabel; UILabel *prolabeltwo; UIProgressView *pro_Download; NSProgress *pro; BOOL canshake; BOOL canvoice; UIImageView *background; NSString *downLoadfile; BOOL firsttime; BOOL changeview; BOOL canbofang; BOOL canback_; Bridge *jo ; SKProductsRequest *productsRequest; BOOL first_Time; BOOL one_Time; BOOL Nothere; NSTimer *timer; NSTimer *timertwo; } @property (copy, nonatomic) NSString *weburl; @property (copy, nonatomic) NSString *iosNumber; @property (strong, nonatomic) NSString *recordFileName; @property (strong, nonatomic) NSString *recordFilePath; @property (copy, nonatomic) NSString *originWav; @property (copy, nonatomic) NSString *backgroundType; @property (copy, nonatomic) NSString *User_id; @property (copy, nonatomic) NSString *UserType; @property (copy, nonatomic) NSString *agentinfo; @property (copy, nonatomic) NSString *gameinfo; @property (copy, nonatomic) NSString *versioninfo; @property (copy, nonatomic) NSArray *agentlist; @property (copy, nonatomic) NSString *channel_id; @property (nonatomic, strong) CTCallCenter *callCenter; @property (nonatomic) BOOL callWasStarted; @property (nonatomic, strong) AMapLocationManager *locationManager; @property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock; @property (nonatomic) int netstate; @property (copy, nonatomic) NSString *Payuser; @property (copy, nonatomic) NSString *Paydata; @property (copy, nonatomic) NSString *showmessage; @property (copy, nonatomic) NSString *market; @property (copy, nonatomic) NSString *version_ios; @property (copy, nonatomic) NSString *game_version_; @property (copy, nonatomic) NSString *game_zip_; @property (copy, nonatomic) NSString *gamedir; @property (copy, nonatomic) NSString *gamestart; @property (copy, nonatomic) NSString *gameconfig; @end @implementation RootVC - (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; } //检测手机晃动 -(void)backgameData:(NSString *)data { } -(void)finishweb {} -(BOOL)canBecomeFirstResponder { return YES; } -(void)initView { // Do any additional setup after loading the view from its nib. NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/index.html?Launchtype=0",self.gamedir,self.gamestart] PathType:2]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:filePath]]; [_webView loadRequest:request]; } -(void)Switch:(NSString *)type Over:(NSString *)directory Game:(NSString *)downurl Data:(NSString *)data { NSLog(@"type%@",type); if (one_Time) { @try { // [[NSNotificationCenter defaultCenter] removeObserver:self name:@"backgameDatatwo" object:nil]; canback_=NO; one_Time=false; Nothere=NO; [WXApiManager sharedManager].delegate = nil; if (backgroundPlayer) { [backgroundPlayer stop]; [backgroundPlayer release]; backgroundPlayer = nil; } fourviewVC *vcNew =[[fourviewVC alloc] initWithNibName:@"fourviewVC" bundle:nil]; [vcNew initinfo:directory downurl:downurl gamedata:data agent:self.agentinfo channel:self.channel_id market:self.market gamedir:self.gamedir agentlist:self.agentlist]; [FuncPublic PushAnimation:self InsertVC:vcNew]; } @catch (NSException *exception) { NSLog(@"%@",exception); // BLYLogInfo(@"agentid=%@;gameid=%@;channelid=%@;game_version=%@;marketid=%@;app_version=%@;game_zip=%@",self.agentinfo,self.gameinfo,self.channel_id,self.game_version_,self.market, self.version_ios,self.game_zip_); //BLYLogError(@"%@",exception); } @finally { NSLog(@"@finally"); } [self performSelector:@selector(canbackone) withObject:nil afterDelay:5.0f]; } // } } -(void)canbackone { one_Time=YES; } - (void)viewDidLoad { if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0) { self.edgesForExtendedLayout = UIRectEdgeNone; } //[self getchannelName]; [super viewDidLoad]; NSString *pathagent=[FuncPublic getFilePath:@"gamedir" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.gamedir= [files objectAtIndex:0]; } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"gameconfig" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.gameconfig= [files objectAtIndex:0]; } } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"gamestart" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.gamestart= [files objectAtIndex:0]; } } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"channel" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.channel_id= [files objectAtIndex:0]; } } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"agent" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.agentinfo= [files objectAtIndex:0]; } } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"appversion" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.iosNumber= [files objectAtIndex:0]; } } if(1) { NSString *pathagent=[FuncPublic getFilePath:@"market" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:pathagent]){ NSArray *files = [fm subpathsAtPath: pathagent ]; NSLog(@"%@",[files objectAtIndex:0]); self.market= [files objectAtIndex:0]; } } if(1) { self.gameconfig=[self.gameconfig stringByReplacingOccurrencesOfString:@"-" withString:@"/"]; self.weburl=[NSString stringWithFormat:@"http://%@.txt",self.gameconfig];; // NSString *pathagent=[FuncPublic getFilePath:@"weburl" PathType:3];// 要列出来的目录 // NSString *weburl_=nil; // // NSFileManager* fm=[NSFileManager defaultManager]; // // if([fm fileExistsAtPath:pathagent]){ // NSArray *files = [fm subpathsAtPath: pathagent ]; // NSLog(@"%@",[files objectAtIndex:0]); // weburl_= [files objectAtIndex:0]; // } // if ([weburl_ isEqual:@"1"]) { // self.weburl=[NSString stringWithFormat:@"%@%@.txt",SERVERNew,self.gameconfig];; // }else if([weburl_ isEqual:@"0"]) // { // self.weburl=[NSString stringWithFormat:@"%@%@.txt",SERVERNewtest,self.gameconfig];; // }else // { // self.weburl=[NSString stringWithFormat:@"%@%@.txt",SERVERNewtest,self.gameconfig];; // // } } [UIApplication sharedApplication].idleTimerDisabled=YES; changeview=YES; firsttime=YES; first_Time=YES; one_Time=YES; canbofang=YES; canback_=YES; Nothere=YES; _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0,DEVW ,DEVH )]; _webView.delegate = self; // _webView.scrollView.showsHorizontalScrollIndicator=NO; _webView.scrollView.showsVerticalScrollIndicator=NO; _webView.scrollView.bounces = NO; _webView.scrollView.showsHorizontalScrollIndicator = NO; _webView.scrollView.scrollEnabled = NO; // [_webView sizeToFit]; [_webView setScalesPageToFit:YES]; // _webView.layer.zPosition=0; [self.view addSubview: _webView]; recorderVC = [[ChatVoiceRecorderVC alloc]init]; recorderVC.vrbDelegate = self; jo = [[Bridge alloc] init]; 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); [self.view addSubview:proimageView]; [proimageView release]; 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]; prolabeltwo=[FuncPublic InstanceLabel:@"重新连接中..." RECT:CGRectMake(0, 250, 568, 38) RECT5:CGRectMake(0, 20, 568, 38) FontName:@"Arial-BoldMT" Red:255 green:11 blue:11 FontSize:22 Target:self.view Lines:0 TAG:-1 Ailgnment:1]; prolabeltwo.alpha=0; // [self performSelector:@selector(timeproblem) withObject:nil afterDelay:6.0f]; timer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(gonet) userInfo:nil repeats:YES]; timertwo = [NSTimer scheduledTimerWithTimeInterval:61.0 target:self selector:@selector(timeproblem) userInfo:nil repeats:NO]; } -(void)timeproblem { if (prolabeltwo!=nil) { prolabeltwo.text=@"网络,配置文件加载有问题,请重新启动游戏!!!"; prolabeltwo.alpha=1; } [timer invalidate]; [timertwo invalidate]; // [NSString stringWithFormat:@"agentid=%@;gameid=%@;channelid=%@;game_version=%@;marketid=%@;app_version=%@;game_zip=%@",self.agentinfo,self.gameinfo,self.channel_id,self.game_version_,self.market, self.version_ios,self.game_zip_] } -(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."); JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"phonestate(2)"]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } } else if ([[call callState] isEqual:CTCallStateDisconnected]) { if (weakSelf.callWasStarted == YES) { weakSelf.callWasStarted = NO; NSLog(@"Call was ended."); JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"phonestate(0)"]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } } }]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground) name:@"applicationWillResignActive" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:@"enterForeground" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopradio:) name:@"stopradio" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(YLbackgameData:) name:@"backgameDatatwo" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(canback) name:@"canbackye" object:nil]; [UIDevice currentDevice].batteryMonitoringEnabled = YES; [[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceBatteryLevelDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) { // Level has changed CGFloat level=[UIDevice currentDevice].batteryLevel; NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel); JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getBattery(%.2f)",level]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; }]; 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; } JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getnetwork(%d)", self.netstate]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; }]; [manager startMonitoring]; } /* 初始方法 */ -(void)canback { canback_=YES; } -(void)YLbackgameData:(NSNotification*)notification { if (canback_) { NSString *data = [notification object]; JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getWebdata('%@')",data]; [context evaluateScript:runJS]; } } /**清除缓存和cookie*/ - (void)cleanCacheAndCookie{ //清除cookies NSHTTPCookie *cookie; NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (cookie in [storage cookies]){ [storage deleteCookie:cookie]; } //清除UIWebView的缓存 [[NSURLCache sharedURLCache] removeAllCachedResponses]; NSURLCache * cache = [NSURLCache sharedURLCache]; [cache removeAllCachedResponses]; [cache setDiskCapacity:0]; [cache setMemoryCapacity:0]; } -(void)enterForeground { if ([[NSThread currentThread] isMainThread]) { NSLog(@"main"); [self cleanCacheAndCookie]; if (Nothere) { JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"appservice(1)"]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } } } -(void)applicationWillResignActive { if ([[NSThread currentThread] isMainThread]) { NSLog(@"main"); [self cleanCacheAndCookie]; if (Nothere) { JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"appservice(2)"]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; //Nothere=NO; } } } -(void)viewWillDisappear:(BOOL)animated { // Nothere=NO; // jo.delegate=nil; } -(void)noterecord:(NSString *)errormsg user:(NSString *)userid agent:(NSString *)agentid game:(NSString *)gameid { NSString *urlStr=[NSString stringWithFormat:@"http://ylyxservice1.0791ts.cn:1089/index.html?{\"data\": {\"agentid\": \"%@\",\"gameid\": \"%@\",\"playerid\": \"%@\",\"msg\": \"%@\",\"packet\": \"123\"},\"app\":\"youle\",\"route\":\"agent\",\"rpc\":\"submit_error\"}",agentid,gameid,@"ios",errormsg]; 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]); }else{ NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding]; NSLog(@"返回结果:%@",result); } } -(void)showmessage_ { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:self.showmessage delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; } -(void)gonet { Reachability *conn = [Reachability reachabilityForInternetConnection]; if (conn.currentReachabilityStatus==NotReachable) { return; } NSString *url_=[NSString stringWithFormat:@"%@%@",self.weburl,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]]; NSURL *urlPath = [NSURL URLWithString:url_]; NSData *requestData = [NSData dataWithContentsOfURL:urlPath]; if(requestData==nil) { return; } [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) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; return; } NSDictionary * obj_return = [str JSONValue]; // NSDictionary *data=[obj_return objectForKey:@"agentlist"]; self.agentlist=[obj_return objectForKey:@"agentlist"]; NSString *one=[obj_return objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { self.showmessage=[obj_return objectForKey:@"showmessage"]; } NSLog(@"%@",self.agentlist); NSString * path=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/version.xml",self.gamedir,self.gamestart] PathType:2]; NSData *dataversion = [[NSData alloc] initWithContentsOfFile:path]; GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:dataversion options:0 error:nil]; NSArray *array = [doc nodesForXPath:@"/game/game" error:nil]; //CityName GDataXMLElement *element = [array firstObject]; self.gameinfo=[element attributeForName:@"id"].stringValue; NSArray *arraythree = [doc nodesForXPath:@"/game/version" error:nil]; GDataXMLElement *elementthree = [arraythree firstObject]; self.versioninfo=[elementthree attributeForName:@"value"].stringValue; // [self noterecord:@"网络差" user:self.User_id agent:self.agentinfo game:self.gameinfo]; for (int x=0; x<[self.agentlist count]; x++) { NSDictionary *infoagent=[self.agentlist objectAtIndex:x]; if([[infoagent objectForKey:@"agentid"] isEqualToString:self.agentinfo]) { one=[infoagent objectForKey:@"showmessage"]; if (![[infoagent objectForKey:@"showmessage"] isEqualToString:@""] ) { 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]) { one=[info objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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]) { one=[infotwo objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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]) { one=[infothree objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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; } } self.version_ios=[infothree objectForKey:@"app_version"]; if ([self.version_ios intValue]>[self.iosNumber intValue]) { if ([self.market intValue]==1) { [self uplevel:[self.game_version_ intValue] download:self.game_zip_]; return; } versionURL=[[NSString alloc]initWithString:[infothree objectForKey:@"app_download"]]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:@"有新的版本更新,点击前往下载!更新过程中可能会白屏,请切到桌面查看下载进度" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; alert.tag=PublicTagfive; return; }else { [self uplevel:[self.game_version_ intValue] download:self.game_zip_]; return; } } } } } } } } } if(self.showmessage!=nil) { if(![self.showmessage isEqualToString:@""]) { [self showmessage_]; return; } } } -(void)viewWillAppear:(BOOL)animated { [WXApiManager sharedManager].delegate = self; [self.navigationController setNavigationBarHidden:YES animated:NO]; Nothere=YES; // jo.delegate=self; if(firsttime) { firsttime=false; [self commoninit]; [self configLocationManager]; [self initCompleteBlock]; }else { return; } if(1) { Reachability *conn = [Reachability reachabilityForInternetConnection]; if (conn.currentReachabilityStatus==NotReachable) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:@"网络没有信号,请检查您的网络状态!还有是否在蜂窝移动网络关闭了应用访问网络的权限,重新连接中!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; prolabeltwo.alpha=1; return; } } NSString *url_=[NSString stringWithFormat:@"%@%@",self.weburl,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]]; NSURL *urlPath = [NSURL URLWithString:url_]; NSData *requestData = [NSData dataWithContentsOfURL:urlPath]; if(requestData==nil) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:@"获取配置文件失败,重新连接中!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; prolabeltwo.alpha=1; return; } [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) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; return; } NSDictionary * obj_return = [str JSONValue]; // NSDictionary *data=[obj_return objectForKey:@"agentlist"]; self.agentlist=[obj_return objectForKey:@"agentlist"]; NSString *one=[obj_return objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { self.showmessage=[obj_return objectForKey:@"showmessage"]; } NSLog(@"%@",self.agentlist); NSString * path=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/version.xml",self.gamedir,self.gamestart] PathType:2]; NSData *dataversion = [[NSData alloc] initWithContentsOfFile:path]; GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:dataversion options:0 error:nil]; NSArray *array = [doc nodesForXPath:@"/game/game" error:nil]; //CityName GDataXMLElement *element = [array firstObject]; self.gameinfo=[element attributeForName:@"id"].stringValue; NSArray *arraythree = [doc nodesForXPath:@"/game/version" error:nil]; GDataXMLElement *elementthree = [arraythree firstObject]; self.versioninfo=[elementthree attributeForName:@"value"].stringValue; // [self noterecord:@"网络差" user:self.User_id agent:self.agentinfo game:self.gameinfo]; for (int x=0; x<[self.agentlist count]; x++) { NSDictionary *infoagent=[self.agentlist objectAtIndex:x]; if([[infoagent objectForKey:@"agentid"] isEqualToString:self.agentinfo]) { one=[infoagent objectForKey:@"showmessage"]; if (![[infoagent objectForKey:@"showmessage"] isEqualToString:@""] ) { 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]) { one=[info objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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]) { one=[infotwo objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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]) { one=[infothree objectForKey:@"showmessage"]; if (![one isEqualToString:@""]) { 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; } } self.version_ios=[infothree objectForKey:@"app_version"]; if ([self.version_ios intValue]>[self.iosNumber intValue]) { if ([self.market intValue]==1) { [self uplevel:[self.game_version_ intValue] download:self.game_zip_]; return; } versionURL=[[NSString alloc]initWithString:[infothree objectForKey:@"app_download"]]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@提醒",gamehallname] message:@"有新的版本更新,点击前往下载!更新过程中可能会白屏,请切到桌面查看下载进度" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; [alert show]; [alert release]; alert.tag=PublicTagfive; return; }else { [self uplevel:[self.game_version_ intValue] download:self.game_zip_]; return; } } } } } } } } } if(self.showmessage!=nil) { if(![self.showmessage isEqualToString:@""]) { [self showmessage_]; return; } } // [self uplevel]; } #pragma mark - alertview delegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (alertView.tag == PublicTagfive) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:versionURL]]; } } -(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-100, 10)]; [pro_Download setProgress:0.0]; [background addSubview:pro_Download]; [pro_Download release]; [background release]; NSURL *downloadUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",downstring,[NSString stringWithFormat:@"?v%08X%08X", arc4random(), arc4random()]]]; downLoadfile=@"gamehall.zip" ;//[NSString stringWithFormat:@"%@.zip",self.gamestart]; // ASIHTTPRequest * requestDownload = [ASIHTTPRequest requestWithURL:downloadUrl]; [requestDownload setDelegate:self]; requestDownload.username=[NSString stringWithFormat:@"download%@",@"test"]; //设置下载路径 [requestDownload setDownloadDestinationPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",downLoadfile] PathType:2]]; //设置缓存路径 [requestDownload setTemporaryFileDownloadPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"caches/%@.tmp",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(@"1"); } - (void)requestFinished:(ASIHTTPRequest *)request { // stateLabel.text=@"下载完成!"; // stateLabel.text=@"正在解压..."; [NSThread detachNewThreadSelector:@selector(unzip) toTarget:self withObject:nil]; // NSLog(@"2"); } - (void)unzip { NSString *zipPath = [FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",downLoadfile] PathType:2]; // NSString *filePath = [FuncPublic getFilePath:[NSString stringWithFormat:@"books/%@",[FuncPublic getStringItem:downLoadfile WithType:0]] PathType:2]; // NSString *filePath=[FuncPublic getFilePath:@"www" PathType:3]; NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@",self.gamedir] PathType:2]; BOOL result = [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; if(result) { ZipArchive *zip = [[ZipArchive alloc] init]; if ([zip UnzipOpenFile:zipPath]) { if ([zip UnzipFileTo: filePath overWrite:YES]) { //此处为空 } } [zip UnzipCloseFile]; [zip release]; [self unzipDone]; } } - (void)unzipDone { //will change //解压完,将zip包删除 //delegate change NSFileManager *fileManager = [[NSFileManager alloc] init]; [fileManager removeItemAtPath:[FuncPublic getFilePath:[NSString stringWithFormat:@"zips/%@",downLoadfile] PathType:2] error:nil]; [fileManager release]; [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 downFileFromServer:downstring]; return; }else { [self initView]; return; } } -(int)getcompareCode { if ([self.version_ios intValue]>=[self.iosNumber intValue]) { return 0; }else { return 1; } return [[FuncPublic GetDefaultInfo:@"getcompareCode"] intValue]; } - (void)webViewDidStartLoad:(UIWebView *)webView { //self.view.userInteractionEnabled=NO; } - (void)webViewDidFinishLoad:(UIWebView *)webView { if(jo.delegate==nil) { JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // Bridge *jo = [[Bridge alloc] init]; context[@"settings"] = jo; context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) { context.exception = exceptionValue; NSLog(@"异常信息:%@", exceptionValue); }; jo.delegate=self; [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"]; [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"]; } if(prolabel!=nil) { [UIView beginAnimations:@"FrameAni"context:nil]; [UIView setAnimationDuration:1.2]; [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]; prolabel=nil; [prolabeltwo removeFromSuperview]; prolabeltwo=nil; [proimageView removeFromSuperview]; proimageView=nil; } -(void) viewDidAppear:(BOOL)animated { } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } //支持的方向 因为界面A我们只需要支持竖屏 - (UIInterfaceOrientationMask)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscape; } -(BOOL)shouldAutorotate{ return YES; } //当前viewcontroller默认的屏幕方向 - 横屏显示 -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeRight; } -(void)dealloc { // SG_RELEASE(versionURL) [self cleanUpAction]; self.completionBlock = nil; SG_RELEASE(_webView); SG_RELEASE(recorderVC); [super dealloc]; } /* 扫一扫 */ -(void)opensaoma { // if([[[UIDevice currentDevice] systemVersion] floatValue] < 7) // { // [FuncPublic ShowAlert:@"版本不支持改功能!"]; // return ; // } // SYQRCodeViewController *qrcodevc = [[SYQRCodeViewController alloc] init]; // qrcodevc.SYQRCodeSuncessBlock = ^(SYQRCodeViewController *aqrvc,NSString *qrString){ // // self.saomiaoLabel.text = qrString; // JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // NSString* runJS=[NSString stringWithFormat:@"saomaData('%@')",qrString]; // // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; // [content evaluateScript:runJS]; // [aqrvc dismissViewControllerAnimated:NO completion:nil]; // }; // qrcodevc.SYQRCodeFailBlock = ^(SYQRCodeViewController *aqrvc){ // // self.saomiaoLabel.text = @"fail~"; // [aqrvc dismissViewControllerAnimated:NO completion:nil]; // }; // qrcodevc.SYQRCodeCancleBlock = ^(SYQRCodeViewController *aqrvc){ // [aqrvc dismissViewControllerAnimated:NO completion:nil]; // // self.saomiaoLabel.text = @"cancle~"; // }; // [self presentViewController:qrcodevc animated:YES completion:nil]; } # pragma - view delegate /* 初始方法 */ -(double)getbattery { CGFloat batterylevel = [UIDevice currentDevice].batteryLevel; return batterylevel; } -(int)getnetwork { return self.netstate; } - (void)networkChanged:(NSNotification *)notification { int state=0; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getnetwork(%d)",state]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } static SystemSoundID shake_sound_male_id = 0; static void completionCallback (SystemSoundID mySSID, void* data) { @try{ // AudioServicesRemoveSystemSoundCompletion (mySSID); NSString *str=(NSString *)data; // self.User_id=str; // UIButton *button = (__bridge UIButton*)data; //if (button.imageView.isAnimating) { // [button.imageView stopAnimating]; //} [[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 { if(Nothere) { NSNumber *viewNumber = [notification object]; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"gameui_stop_voice(%@)",viewNumber.description]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } } -(void)voicePlaying:(NSString *)type { if ([type isEqualToString:@"1"]) { canbofang=YES; } else { canbofang=NO; } } -(void)media:(NSString *)url Type:(NSString *)history Audio:(NSString *)userid { self.User_id=userid; self.recordFileName = [FuncPublic GetCurrentTimeString]; NSURL *urlPath = [NSURL URLWithString:url]; NSData *data = [NSData dataWithContentsOfURL:urlPath]; NSString *filename = [FuncPublic GetPathByFileName:self.recordFileName ofType:@"amr"]; [data 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); JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"gameui_play_voice(%@)",self.User_id]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; }else NSLog(@"amr转wav失败"); } - (void)VoiceRecorderBaseVCRecordFinish:(NSString *)_filePath fileName:(NSString*)_fileName{ NSLog(@"录音完成,文件路径:%@ %@",_filePath,_fileName); // [self setLabelByFilePath:_filePath fileName:_fileName convertTime:0 label:nil]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; AVAudioPlayer *play = [[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:_filePath] error:nil]autorelease]; NSTimeInterval interval= play.duration; NSInteger time = round(interval); //4.播放 if (play == nil) { NSLog(@"ERror creating player: %@", [play description]); }else{ // [play prepareToPlay]; // [play play]; // 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:_filePath],&shake_sound_male_id); // AudioServicesAddSystemSoundCompletion(shake_sound_male_id, NULL, NULL, completionCallback, (__bridge void*) self.User_id); // // AudioServicesPlaySystemSound(shake_sound_male_id); // // JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // NSString* runJS=[NSString stringWithFormat:@"gameui_play_voice(%@)",self.User_id]; // // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; // [content evaluateScript:runJS]; } NSString *amrPath = [FuncPublic GetPathByFileName: _fileName ofType:@"amr"]; if ([VoiceConverter ConvertWavToAmr:_filePath amrSavePath:amrPath]){ NSData *test=[NSData dataWithContentsOfFile:amrPath]; AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //接收类型不一致请替换一致text/html或别的 manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"audio/amr", nil]; NSString *string=@"http://gameapi.0791ts.cn/api/UpLoad/PostFile"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat =@"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.amr", str]; [manager POST:string parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) { // NSData *imageData =UIImageJPEGRepresentation([UIImage imageNamed:@"sharelogo.jpg"],1); //上传的参数(上传图片,以文件流的格式) [formData appendPartWithFileData:test name:@"file" fileName:fileName mimeType:@"audio/amr"]; } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) { NSString *audiourl=[NSString stringWithFormat:@"http://gameapi.0791ts.cn/upload/%@",fileName]; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getaudiourl('%@',%ld)",audiourl,time]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; //上传成功 NSLog(@"3"); } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) { //上传失败 NSLog(@"1"); }]; NSLog(@"124"); }else NSLog(@"wav转amr失败"); } -(void)prepareaudio { self.originWav =[VoiceRecorderBaseVC getCurrentTimeString];//[dateformat stringFromDate:[NSDate date]];// if([FuncPublic ifauth]==0) { JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"alert('%@需要访问您的麦克风,请启用麦克风-设置/隐私/麦克风!')",gamehallname];//需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风! // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; return; } //开始录音 [recorderVC beginRecordByFileName:self.originWav]; } - (BOOL)canRecord { __block BOOL bCanRecord = YES; if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) { [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) { if (granted) { bCanRecord = YES; } else { bCanRecord = NO; } }]; } } return bCanRecord; } -(void)src:(NSString *)message Isloop:(NSString *)message2 { NSURL *url_=nil; NSString * string=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@/%@/assets/wav/%@",self.gamedir,self.gamestart,message] PathType:2]; url_=[NSURL URLWithString:string]; // [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; if(message==nil||[message isEqualToString:@""]) { return; } if (![[NSFileManager defaultManager] fileExistsAtPath:string]) { return; } if([message2 intValue]==0) { // //2.创建播放器(注意:一个AVAudioPlayer只能播放一个url) // AVAudioPlayer *audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url_ error:Nil]; // // //3.缓冲 // [audioPlayer prepareToPlay]; // // //4.播放 // [audioPlayer play]; AVAudioSession *audioSession = [AVAudioSession sharedInstance]; NSError *err = nil; [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)url_,&shake_sound_male_id); AudioServicesPlaySystemSound(shake_sound_male_id); } if([message2 intValue]==1) { self.backgroundType=message; if (backgroundPlayer) { [backgroundPlayer stop]; [backgroundPlayer release]; 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) { [backgroundPlayer stop]; [backgroundPlayer release]; backgroundPlayer = nil; } } } } - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { NSLog(@"nothing "); } -(NSString *)getOther { NSString *path=[FuncPublic getFilePath:@"other" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:path]){ NSArray *files = [fm subpathsAtPath: path ]; NSLog(@"%@",[files objectAtIndex:0]); return [files objectAtIndex:0]; } return @""; } -(NSString *)getothername:(NSString *)othername { NSString *path=[FuncPublic getFilePath:othername PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:path]){ NSArray *files = [fm subpathsAtPath: path ]; NSLog(@"%@",[files objectAtIndex:0]); return [files objectAtIndex:0]; } return @""; } -(void)accreditlogin { //return; // [self opensaoma]; //return; [WXApiRequestHandler sendAuthRequestScope: kAuthScope State:kAuthState OpenID:kAuthOpenID InViewController:self]; } #pragma mark - 设置弹出提示语 - (void)setupAlertController { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]; [alert addAction:actionConfirm]; [self presentViewController:alert animated:YES completion:nil]; } - (void)managerDidRecvMessageResponse:(SendMessageToWXResp *)response { if(response.errCode==0) { JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"sharesuccess(2,%d)",[self.UserType intValue]]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } } - (void)managerDidRecvAuthResponse:(SendAuthResp *)response { if (response.code==nil) { 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]); }else{ NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding]; NSLog(@"返回结果:%@",result); } 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:@""]; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"sharelogin('%@','%@','%@','%@','%@','%@','%@')",[obj_returntwo objectForKey:@"openid"],[obj_returntwo objectForKey:@"headimgurl"],nickname,[obj_returntwo objectForKey:@"sex"],[self danbian:[obj_returntwo objectForKey:@"city"]],[self danbian:[obj_returntwo objectForKey:@"province"]],[obj_returntwo objectForKey:@"unionid"]]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; } -(NSString *)danbian:(NSString *)str { return [str stringByReplacingOccurrencesOfString:@"'" withString:@""]; } - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (motion == UIEventSubtypeMotionShake) { if(canshake) { JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"shakeEnd()"]; // NSString * runJS = @"sharelogin(openid,headimgurl,nickname,sex,city,Province,unionid)"; [content evaluateScript:runJS]; 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)startshake { canshake=YES; } -(void)stopshake { canshake=false; } -(NSString *)getchannelName { NSString *path=[FuncPublic getFilePath:@"channel" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:path]){ NSArray *files = [fm subpathsAtPath: path ]; NSLog(@"%@",[files objectAtIndex:0]); return [files objectAtIndex:0]; } return @""; } -(NSString *)getmarketname { NSString *path=[FuncPublic getFilePath:@"market" PathType:3];// 要列出来的目录 NSFileManager* fm=[NSFileManager defaultManager]; if([fm fileExistsAtPath:path]){ NSArray *files = [fm subpathsAtPath: path ]; NSLog(@"%@",[files objectAtIndex:0]); return [files objectAtIndex:0]; } return @""; } -(void)SwitchShake:(NSString *)voice { if([voice intValue]==1) { canvoice=YES; }else { canvoice=NO; } } -(NSString *)gamepastetext { //NSString * strBuildID = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleIdentifier"]; UIPasteboard * myPasteboard = [UIPasteboard generalPasteboard];//[UIPasteboard pasteboardWithName:strBuildID create:NO]; return myPasteboard.string; } -(void)gameCopytext:(NSString *)text { //应用内单独使用时 //NSString * strBuildID = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleIdentifier"]; UIPasteboard * myPasteboard = [UIPasteboard generalPasteboard];// [UIPasteboard pasteboardWithName:strBuildID create:YES]; myPasteboard.string = text; } -(void)Openurl:(NSString *)url Title:(NSString *)title Data:(NSString *)data { if(first_Time) { Nothere=NO; threeView *detail = [[threeView alloc] initWithNibName:@"threeView" bundle:nil]; [detail Openurl:url Title:title Data:data]; [FuncPublic PushAnimation:self InsertVC:detail]; first_Time=NO; } [self performSelector:@selector(canopen) withObject:nil afterDelay:3.0f]; } -(void)canopen { first_Time=YES; } -(void)browser:(NSString *)url { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]]; } -(void)vibrator:(NSString *)time { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); } -(void)repeatvibrator:(NSString *)repeat { if([repeat intValue]==-1) { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); }else { // AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate, NULL, NULL, soundCompleteCallback, NULL); AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); } } -(void)canclevibrator { AudioServicesDisposeSystemSoundID(kSystemSoundID_Vibrate); } //-(void)sharefriend:(NSString *)sharefriend type:(NSString *)type webpageUrl:(NSString *)webpageUrl title:(NSString *)title description:(NSString *)description -(void)friends:(NSString *)one Sharetype:(NSString *)two Url:(NSString *)three Toptitle:(NSString *)four Descript:(NSString *)five { self.UserType=one; NSLog(@"%@",two); enum WXScene currentScene; int friend = [one intValue]; if(friend==1) { currentScene=WXSceneSession; }else { currentScene=WXSceneTimeline; } if([two intValue]==1) { [WXApiRequestHandler sendLinkURL:three TagName:[NSString stringWithFormat:@"%@游戏下载链接",gamehallname] Title:four Description:five ThumbImage:[UIImage imageNamed:@"sharelogo.png"] InScene:currentScene]; }else if([two intValue]==2) { 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 { 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]; } } -(int)getGameinstall:(NSString *)gamename { NSFileManager *fileManager = [[NSFileManager alloc] init]; NSString *filePath=[FuncPublic getFilePath:[NSString stringWithFormat:@"%@",gamename] PathType:2]; if ([fileManager fileExistsAtPath:filePath]) { NSLog(@"文件%@存在",gamename); return 1; }else { return 0; } } /* 苹果内支付 */ -(void)getGameplay:(NSString *)jsondata { } /* 地图 */ - (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{ NSString *jsondata= [ NSString stringWithFormat:@"{\"address\":\"%@\",\"city\":\"%@\",\"cityCode\":\"%@\",\"country\":\"%@\",\"district\":\"%@\",\"latitude\":%f,\"longitude\":%f,\"province\":\"%@\",\"street\":\"%@路\"}",regeocode.formattedAddress,regeocode.city,regeocode.citycode,regeocode.country,regeocode.district,location.coordinate.latitude,location.coordinate.longitude,regeocode.province,regeocode.street]; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getlocationinfo('%@')",jsondata]; [content evaluateScript:runJS]; } @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{ NSString *jsondata= [ NSString stringWithFormat:@"{\"address\":\"%@\",\"city\":\"%@\",\"cityCode\":\"%@\",\"country\":\"%@\",\"district\":\"%@\",\"latitude\":%f,\"longitude\":%f,\"province\":\"%@\",\"street\":\"%@路\"}",reGeocode.formattedAddress,reGeocode.city,reGeocode.citycode,reGeocode.country,reGeocode.district,location.coordinate.latitude,location.coordinate.longitude,reGeocode.province,reGeocode.street]; JSContext *content = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; NSString* runJS=[NSString stringWithFormat:@"getlocationinfo('%@')",jsondata]; [content evaluateScript:runJS]; } @catch (NSException * e) { NSLog(@"Exception: %@", e); } } } } -(void)startlocation:(NSString *)Type { if ([Type isEqualToString:@"1"]) { [self.locationManager startUpdatingLocation]; }else { [self reGeocodeAction]; } } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end