| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736 |
- //
- // AppDelegateBase.m
- // iSales-UWAVER
- //
- // Created by Ray on 2018/8/9.
- // Copyright © 2018 United Software Applications, Inc. All rights reserved.
- //
- #import "AppDelegateBase.h"
- #import "UILabel+FontAppearance.h"
- #import "MainViewController.h"
- #import "RAPDFViewController.h"
- #import "ZipArchive.h"
- #import "DefaultAppearance.h"
- #import "OLDataProvider.h"
- #import "SelectUploadOrderViewController.h"
- #import "iSalesDB.h"
- #import "RANetwork.h"
- #import "NotificationNameCenter.h"
- #import "CustomerEditViewController.h"
- #import "CreateOrderViewController.h"
- #import "OrderDetailViewController.h"
- #import "AddressEditorViewController.h"
- #import "config.h"
- #import "RASingleton.h"
- #ifdef GOOGLE_ANALYTICS
- #import "Analytics.h"
- #import "GoogleAnalyst.h"
- #endif
- #import "ERPUtils.h"
- #import "RANetwork.h"
- #import "RASingleton.h"
- #ifdef BACKORDER_PROCESS
- #import "RAOrderEditorViewController.h"
- #endif
- #import "RAConvertor.h"
- //#import "config.h"
- #define UNZIP_OPEN_FAILED 0
- #define UNZIP_SUCCESS 1
- #define UNZIP_NO_SPACE 2
- #define UNZIP_FILE_DAMAGE 3
- @interface AppDelegateBase ()
- @end
- @implementation AppDelegateBase
- {
- #ifdef USE_MFI_SCANNER
-
- DeviceInfo* _deviceInfoToTrigger;
- #endif
-
- NSMutableArray* _feedbackStack;
-
- id<ScannerEventsFeedback> _eventsFeedback;
- }
- #ifdef USE_MFI_SCANNER
-
- @synthesize ScanApi;
- #endif
- @synthesize ScanApiConsumer;
- @synthesize scanApiVersion;
- @synthesize price_hidden = _price_hidden;
- #pragma mark - Window Property
- // 重写 window 的 getter,从 SceneDelegate 获取
- - (UIWindow *)window {
- if (@available(iOS 13.0, *)) {
- // iOS 13+ 从 SceneDelegate 获取 window
- NSSet *connectedScenes = [UIApplication sharedApplication].connectedScenes;
- for (UIScene *scene in connectedScenes) {
- if ([scene isKindOfClass:[UIWindowScene class]]) {
- UIWindowScene *windowScene = (UIWindowScene *)scene;
- for (UIWindow *window in windowScene.windows) {
- if (window.isKeyWindow) {
- return window;
- }
- }
- // 如果没有 key window,返回第一个 window
- return windowScene.windows.firstObject;
- }
- }
- }
- return nil;
- }
- #pragma mark - Global Parameter
- //- (NSMutableDictionary *)globalParameters {
- // if (!_globalParameters) {
- // _globalParameters = [NSMutableDictionary dictionary];
- // }
- // return _globalParameters;
- //}
- //
- //- (void)setGlobalParameter:(id)param forKey:(NSString *)key {
- // if (param == nil || key == nil) {
- // return;
- // }
- // [self.globalParameters setObject:param forKey:key];
- //}
- //
- //- (id)globalParameterForKey:(NSString *)key {
- // if (key == nil) {
- // return nil;
- // }
- // return [self.globalParameters objectForKey:key];
- //}
- #pragma mark - Setter
- //
- //- (void)setAlert_sold_in_quantities:(bool)alert_sold_in_quantities
- //{
- // _alert_sold_in_quantities =alert_sold_in_quantities;
- //}
- - (void)setUrgencyDic:(NSMutableDictionary *)urgencyDic {
- _urgencyDic = urgencyDic;
- [RASingleton.sharedInstance setGlobalParameter:_urgencyDic forKey:@"urgencyDic"];
- }
- - (void)setCan_see_price:(bool)can_see_price {
- _can_see_price = can_see_price;
- [RASingleton.sharedInstance setGlobalParameter:@(_can_see_price) forKey:@"can_see_price"];
- }
- - (void)setPrice_hidden:(bool)price_hidden {
- _price_hidden = price_hidden;
- [RASingleton.sharedInstance setGlobalParameter:@(_price_hidden) forKey:@"price_hidden"];
-
- #ifdef RA_NOTIFICATION
- [ActiveViewController Notify:@"" Message:RA_NOTIFICATION_UPDATE_PRICE];
- #else
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
-
- [avc showHidePrice];
- #endif
- }
- - (void)setOffline_mode:(bool)offline_mode {
- _offline_mode = offline_mode;
- [RASingleton.sharedInstance setGlobalParameter:@(_offline_mode) forKey:@"offline_mode"];
- }
- //- (void)setUser:(NSString *)user {
- // _user = user;
- // RASingleton.sharedInstance.user = user;
- // [RASingleton.sharedInstance setGlobalParameter:_user forKey:@"user"];
- //}
- - (void)setUser_type:(long)user_type
- {
- _user_type = user_type;
- }
- //- (void)setPassword:(NSString *)password {
- // _password = password;
- // [RASingleton.sharedInstance setGlobalParameter:_password forKey:@"password"];
- //}
- #pragma mark - Normal
- -(void) set_priceHidden:(bool)price_hidden
- {
- [self setPrice_hidden:price_hidden];
- }
- -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
- {
- if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
- return;
- }
-
-
- #ifdef RA_NOTIFICATION
- [ActiveViewController Notify:@"ContactListViewController" Message:RA_NOTIFICATION_REFRESH_UI];
- //切换账号应该不需要刷新wishlist,此处如果刷新,会使wishlist新建订单自动添加出错。
- // [ActiveViewController Notify:@"WatchListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
-
- #else
- [((MainViewController*)self.main_vc) reloadContact:false immediately:false];
- [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
- #endif
-
-
- _customerInfo=customerInfo;
-
- // DebugLog(@"%@",_customerInfo.class);
- // DebugLog(@"%@",customerInfo.class);
- // int count=customerInfo[@"count"];
- //assert(count==0);
-
- }
- -(void) set_main_button_panel
- {
- return;
- // dispatch_async(dispatch_get_main_queue(), ^{
- // if(self.main_vc==nil)
- // return;
- // MainViewController * main_vc= (MainViewController*)self.main_vc;
- // if(self.user_type==USER_ROLE_CUSTOMER)
- // {
- // main_vc.customer_bp.hidden=false;
- // main_vc.employee_bp.hidden = true;
- // }
- // else
- // {
- // main_vc.customer_bp.hidden=true;
- // main_vc.employee_bp.hidden = false;
- // }
- // });
- }
- //#ifdef SCANNER_ORDER
- //- (void)updateScanButton:(BOOL)enable
- //{
- // MainViewController * mainvc=(MainViewController * )self.main_vc;
- // mainvc.btnScan.enabled = enable;
- //}
- //#endif
- -(void) update_count_mark
- {
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if(self.main_vc==nil)
- return;
-
- MainViewController * main_vc= (MainViewController*)self.main_vc;
-
- //contact button
-
-
-
- if(RASingleton.sharedInstance.user==nil)
- {
-
-
- [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
-
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- main_vc.btnContact.hidden = YES;
-
- }
- else
- {
-
-
-
- NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
- NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
- if(self.customerInfo==nil)
- {
- // contact=@"No Name"; if(customerinfo==nil)
- // {
- contact=@"Select Contact";
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- }
- else
- {
-
- if(contact==nil||contact.length==0)
- {
- contact=@"No Name";
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- }
- else
- {
- [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
- }
- }
-
- NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
- if(contact.length>0)
- [arr_contact addObject:contact];
- if(customer.length>0)
- [arr_contact addObject:customer];
-
- NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
-
-
- [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
-
-
- }
- //cart
- if(RASingleton.sharedInstance.user==nil||self.cart_count==0)
- {
- main_vc.label_ccount.hidden = true;
- main_vc.label_cccount.hidden=true;
- }
- else
- {
-
- NSString* strcount;
- if(self.cart_count>999)
- strcount=@"999+";
- else
- strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
-
- main_vc.label_ccount.text = strcount;
- if(strcount.length==1)
- main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
- if(strcount.length==2)
- main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
- if(strcount.length==3)
- main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
- if(strcount.length==4)
- main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
-
- main_vc.label_ccount.hidden = false;
-
-
- main_vc.label_cccount.text = strcount;
- if(strcount.length==1)
- main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
- if(strcount.length==2)
- main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
- if(strcount.length==3)
- main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
- if(strcount.length==4)
- main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
-
- main_vc.label_cccount.hidden = false;
-
-
- }
-
- //wishlist
- if(RASingleton.sharedInstance.user==nil||self.wish_count==0)
- {
- main_vc.label_wcount.hidden = true;
- main_vc.label_cwcount.hidden = true;
-
- }
- else
- {
-
- NSString* strcount;
- if(self.wish_count>999)
- strcount=@"999+";
- else
- strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
-
- main_vc.label_wcount.text = strcount;
- if(strcount.length==1)
- main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
- if(strcount.length==2)
- main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
- if(strcount.length==3)
- main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
- if(strcount.length==4)
- main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
-
-
- main_vc.label_wcount.hidden = false;
-
-
-
- main_vc.label_cwcount.text = strcount;
- if(strcount.length==1)
- main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
- if(strcount.length==2)
- main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
- if(strcount.length==3)
- main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
- if(strcount.length==4)
- main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
-
-
- main_vc.label_cwcount.hidden = false;
-
-
- }
-
-
-
-
- });
-
-
- }
- -(void) closeOrder
- {
- self.order_code = nil;
- self.order_customer_id = nil;
-
-
- if(self.user_type!=USER_ROLE_CUSTOMER)
- {
- self.customerInfo = nil;
- self.contact_id = nil;
- }
-
- // [self SetMode:nil];
- // [self SetSo:nil];
-
-
-
-
-
-
- #ifdef RA_NOTIFICATION
- [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
- #else
- [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
- [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
- #endif
-
-
- // [self updateScanButton:false];
-
- }
- -(void) switchToPreviousVC
- {
- MainViewController * main_vc= (MainViewController*)self.main_vc;
-
- [main_vc switchToPreviousVC];
- }
- -(void) SetMode:(NSString*)mode1
- {
-
- __block NSString* blockmode= mode1;
- dispatch_async(dispatch_get_main_queue(), ^{
-
- if(self.offline_mode)
- blockmode =@"Regular Mode";
-
- if(self.main_vc==nil)
- return;
-
- MainViewController * main_vc= (MainViewController*)self.main_vc;
-
- if(RASingleton.sharedInstance.user==nil)
- {
-
- NSString* title = [NSString stringWithFormat:@"Sign in"];
- [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
-
- [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
-
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- main_vc.btnContact.hidden = YES;
-
- main_vc.labelMode.text=nil;
- [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
- return;
- }
- else
- {
- #ifndef SCANNER_ORDER
- main_vc.btnContact.hidden = NO;
- #endif
- if(self.user_type==USER_ROLE_CUSTOMER)
- {
- NSString* title = [NSString stringWithFormat:@"%@",RASingleton.sharedInstance.user];
- [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
- main_vc.labelMode.text=nil;
- [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
- }
- else
- {
- if([blockmode isEqualToString:@"Regular Mode"])
- {
- self.mode=@"RM";
- NSString* title = RASingleton.sharedInstance.user;
- [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
-
- main_vc.labelMode.text=self.mode;
- [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
- }
- else
- {
-
- self.mode=@"TM";
- NSString* title = RASingleton.sharedInstance.user;
- [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
-
- main_vc.labelMode.text=self.mode;
- [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
- }
-
-
-
- }
-
- NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
- NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
- if(self.customerInfo==nil)
- {
- // contact=@"No Name"; if(customerinfo==nil)
- // {
- contact=@"Select Contact";
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- }
- else
- {
-
- if(contact==nil||contact.length==0)
- {
- contact=@"No Name";
- [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
- }
- else
- {
- [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
- }
- }
-
- NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
- if(contact.length>0)
- [arr_contact addObject:contact];
- if(customer.length>0)
- [arr_contact addObject:customer];
-
- NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
-
-
- [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
- }
- });
- }
- -(void) SetSo:(NSString *)So
- {
-
- dispatch_async(dispatch_get_main_queue(), ^{
- if(self.main_vc==nil)
- return;
-
- MainViewController * main_vc= (MainViewController*)self.main_vc;
-
- if (self.user_type == USER_ROLE_CUSTOMER) {
- if (So == nil) {
- // 释放订单
- [RASingleton sharedInstance].currentOrderIsMerged = NO;
- }
- }
-
- if(RASingleton.sharedInstance.user==nil)
- {
-
- // NSString* title = [NSString stringWithFormat:@"Sign in"];
- main_vc.labelSo.text=nil;
-
- return;
- }
- else
- {
- {
- if(So.length==0)
- main_vc.labelSo.text=nil;
- else
- {
- NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
- main_vc.labelSo.text=text;
- }
- }
- }
- });
- }
- //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
- // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
- // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
- // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
- // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
- // UINavigationController* navigationController = (UINavigationController*)rootViewController;
- // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
- // } else if (rootViewController.presentedViewController) {
- // UIViewController* presentedViewController = rootViewController.presentedViewController;
- // return [self topViewControllerWithRootViewController:presentedViewController];
- // } else {
- // return rootViewController;
- // }
- //}
- //- (UIViewController*)topViewController {
- // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
- //}
- //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
- //// // Get topmost/visible view controller
- // UIViewController *currentViewController = [self topViewController];
- //
- // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
- //
- // return UIInterfaceOrientationMaskPortrait;
- // }
- ////
- //// // Only allow portrait (standard behaviour)
- // return UIInterfaceOrientationMaskAll;
- //}
- void UncaughtExceptionHandler(NSException *exception) {
-
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
- NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
- NSString *versionNum = @"";
- versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
-
- versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
- /**
- * 获取异常崩溃信息
- */
- NSArray *callStack = [exception callStackSymbols];
- NSString *reason = [exception reason];
- NSString *name = [exception name];
- NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
-
- content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
-
-
- NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
- if ([RASingleton sharedInstance].currentDB) {
- [iSalesDB close_db:[RASingleton sharedInstance].currentDB];
- }
- [iSalesDB execSql:sql];
-
-
- dispatch_async(dispatch_get_main_queue(), ^{
- AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
- [appDelegate writeUrgencyCache];
- });
-
-
- #ifdef SCANNER_ORDER
- AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
- [appDelegate saveUploadTasks];
- #endif
- }
- - (void)handleErrorLog {
-
- #ifdef SCANNER_ORDER
- return;
- #else
- __block NSMutableArray *err_array = [NSMutableArray array];
- [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
-
- const char *version_char = (char *)sqlite3_column_text(stmt, 0);
- const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
- const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
-
- if (version_char == NULL)
- version_char = "";
- if (errlog_char == NULL)
- errlog_char = "";
- if (dateTime_char == NULL)
- dateTime_char = "";
-
- NSString *version_str = [NSString stringWithUTF8String:version_char];
- NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
- NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
-
- NSDictionary *err_dic = @{
- @"version" : version_str,
- @"errlog" : errlog_str,
- @"time" : dateTime_str
- };
-
- [err_array addObject:err_dic];
-
-
- }];
-
- if (err_array.count) {
- // 首先上传
- for (NSDictionary *err_dic in err_array) {
-
- NSString *version = [err_dic objectForKey:@"version"];
- NSString *errlog = [err_dic objectForKey:@"errlog"];
- NSString *time = [err_dic objectForKey:@"time"];
-
- NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
-
- // NSDictionary *ret = [RANetwork err_log:errlog result:result module:@"crash" code:0];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [RANetwork request_err_log:errlog result:result module:@"crash" code:0 completionHandler:^(NSMutableDictionary *result) {
-
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
-
- // 上传成功之后清除纪录
- if ([[result objectForKey:@"result"] integerValue] == 2) {
-
- [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
- }
-
-
-
- });
-
- }];
- });
-
- }
-
-
- }
-
- #endif
- }
- - (void)dealWithUrgencyFile {
-
- NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
-
- if (tmp_urgencyDic.allKeys.count > 2) {
-
- [self.urgencyDic removeAllObjects];
- [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
-
-
- // UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
-
- NSString *user = [tmp_urgencyDic objectForKey:@"user"];
- if (![user isEqualToString:RASingleton.sharedInstance.user]) {
- return;
- }
-
- BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
- if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
- return;
- }
-
- id count = [tmp_urgencyDic objectForKey:@"count"];
- int level_count = count ? (int)[count integerValue] : 0;
-
- if (!level_count) {
- return;
- }
-
- for (int i = 0; i < level_count; i++) {
-
- NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
-
- NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
-
- NSString *className = [urgencyDic objectForKey:@"class_name"];
-
- NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
-
- NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
-
- dispatch_async(dispatch_get_main_queue(), ^{
-
- if ([className isEqualToString:@"CustomerEditViewController"]) {
- // CustomerEditViewController
-
- NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
- BOOL new_customer = [urgencyDic objectForKey:@"new_customer"];
-
- NSMutableDictionary *params = [NSMutableDictionary dictionary];
-
- [params setValue:contact_id forKey:@"contact_id"];
-
- CustomerEditViewController * cuseditVC =[[CustomerEditViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
-
- cuseditVC.bnewcustomer=new_customer;
- cuseditVC.url_type = URL_RESTORE;
- cuseditVC.request_url= new_customer ? URL_NEW_CUSTOMER : URL_EDIT_CUSTOMER;
-
- cuseditVC.params = params;
- cuseditVC.content_data_download = restored_data;
-
- // cuseditVC.delegate=self;
-
-
- MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
- [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
- [mainVC.navigationController pushViewController:cuseditVC animated:false];
-
-
-
- } else if ([className isEqualToString:@"CreateOrderViewController"] || [className isEqualToString:@"RAOrderEditorViewController"]) {
- // CreateOrderViewController
-
- NSString *order_code = [urgencyDic objectForKey:@"order_code"];
- int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
- NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
- NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
- NSString *so = [urgencyDic objectForKey:@"order_so"];
- self.order_customer_id = order_customer_id;
-
- [RANetwork request_open_order:order_code completionHandler:^(NSMutableDictionary *result) {
- NSDictionary* order_json = result;
-
- // [waitalert dismissViewControllerAnimated:YES completion:nil];
- if([[order_json valueForKey:@"result"] intValue]==2)
- {
-
- self.order_code = order_code;
- self.order_status = order_status;
- [self SetSo:so];
-
- if (userType != USER_ROLE_CUSTOMER) {
-
- [RANetwork request_contactinfo:order_customer_id completionHandler:^(NSMutableDictionary *result) {
- self.customerInfo = [result[@"customerInfo"] mutableCopy];
- self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
- }];
-
- // self.customerInfo = [[[RANetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
- //
- // self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
- }
-
-
-
-
-
- #ifdef RA_NOTIFICATION
- [ActiveViewController Notify:@"CartViewController,OrderListViewController" Message:RA_NOTIFICATION_RELOAD_DATA];
- #else
- MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
- [mainVC reloadOrder:true immediately:false];
- [mainVC reloadCart:true immediately:false];
- #endif
-
- }
- else
- {
- // MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
-
- [RAUtils message_box:@"Open Order" message:[order_json valueForKey:@"err_msg"] completion:nil];
- }
-
- }];
-
-
-
- // 再place order
- NSMutableDictionary *params = [NSMutableDictionary dictionary];
-
- if ([className isEqualToString:@"CreateOrderViewController"]) {
- CreateOrderViewController * orderinfoVC = [[CreateOrderViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
-
- orderinfoVC.disable_dropdown_refresh=true;
- orderinfoVC.url_type = URL_RESTORE;
- orderinfoVC.request_url=URL_CARTDELIVERY;
- orderinfoVC.params = params;
- orderinfoVC.content_data_download = restored_data;
- orderinfoVC.resumeOrder = YES;
- MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
- [mainVC.navigationController pushViewController:orderinfoVC animated:true];
- }
- #ifdef BACKORDER_PROCESS
- else if ([className isEqualToString:@"RAOrderEditorViewController"]) {
-
-
-
- RAOrderEditorViewController *orderEditorVC = [[RAOrderEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
- [orderEditorVC recoveryFromUrgencyDic:urgencyDic];
- MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
- [mainVC.navigationController pushViewController:orderEditorVC animated:YES];
- }
- #endif
-
-
- } else if ([className isEqualToString:@"AddressEditorViewController"]) {
- // AddressEditorViewController
-
- AddressEditorViewController * addressVC = [[AddressEditorViewController alloc] initWithNibName:@"CommonEditor.iPad" bundle:nil];
-
- addressVC.url_type = URL_RESTORE;
- addressVC.request_url=URL_ADDRESS_EDOTOR;
-
- NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
-
- params[@"is_subaction"]=@"true";
- addressVC.params = params;
- addressVC.content_data_download = restored_data;
-
- MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
- [mainVC.navigationController pushViewController:addressVC animated:true];
-
- }// class_name
-
- });
-
- }
-
-
- }
- }
- - (void)handleUrgencyFile {
-
- __weak typeof(self) weakself = self;
-
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
-
- if (weakself) {
-
- __strong typeof(weakself) strongself = weakself;
-
- [strongself dealWithUrgencyFile];
- }
-
-
-
-
- });
-
- }
- - (void)writeUrgencyCache {
- if (!RASingleton.sharedInstance.user) {
- return;
- }
-
- NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
- NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",RASingleton.sharedInstance.user]];
-
- // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
- [self.urgencyDic writeToFile:urgencyFile atomically:NO];
-
- // Place Order恢复是否能提交订单
- [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
- [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
- if ([RASingleton sharedInstance].currentOrderIsMerged && [RASingleton sharedInstance].permissions_submit_order) {
- [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
- }
- }
- - (NSMutableDictionary *)readUrgencyCache {
- // 检查本地urgency文件,存在则加载进_urgencyDic
- NSFileManager *manager = [NSFileManager defaultManager];
- NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
- NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",RASingleton.sharedInstance.user]];
- NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
- if ([manager fileExistsAtPath:urgencyFile]) {
-
- resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
- [manager removeItemAtPath:urgencyFile error:nil];
-
- }
-
- self.urgencyDic = [NSMutableDictionary dictionary];
-
- return resultDic;
- }
- - (void)initialExceptionHandler {
- if (exception_switch == 1) {
- NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
- }
-
- }
- - (void)becomeObserver {
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
- }
- - (void)dealloc {
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- #ifdef SCANNER_ORDER
- -(void) setAddress:(NSString *)address
- {
-
- _address = address;
- _uploadurl = [address stringByAppendingPathComponent:URL_SCAN_UPLOAD];// [NSString stringWithFormat:@"%@%@",address,URL_SCAN_UPLOAD];
- NSString * file = [NSString stringWithFormat:URL_SCAN_DOWNLOAD,[RADataProvider getSiteName]];
- _downloadurl =[address stringByAppendingPathComponent:file] ; // [NSString stringWithFormat:@"%@%@",address,URL_SCAN_DOWNLOAD];
-
-
-
- }
- #endif
- #ifdef GOOGLE_ANALYTICS
- - (void)setUpGoogleAnalytics {
-
- // 初始化Google Analytics
- NSError *configureError;
- [[GGLContext sharedInstance] configureWithError:&configureError];
-
- if (configureError) {
- DebugLog(@"congigure googleAnalytics error: %@",configureError);
- }
-
- GAI *gai = [GAI sharedInstance];
- gai.trackUncaughtExceptions = YES;
-
- id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
- // Enable IDFA collection.
- tracker.allowIDFACollection = YES;
- // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
-
- // 调试使用
- // gai.logger.logLevel = kGAILogLevelVerbose;
- // [[GAI sharedInstance] setDryRun:YES];
- //
- }
- #endif
- //-(void)test_descrypt
- //{
- // sqlite3 *db = [iSalesDB get_db];
- //
- // int result= [iSalesDB AddExFunction:db];
- //
- // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
- // sqlite3_stmt * statement;
- //
- //
- // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
- // {
- //
- //
- // while (sqlite3_step(statement) == SQLITE_ROW)
- // {
- //
- //
- // char *url = (char*)sqlite3_column_text(statement, 0);
- // if(url==nil)
- // url="";
- // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
- // DebugLog(nsurl);
- //
- //
- //
- //
- // }
- // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
- //
- //
- // sqlite3_finalize(statement);
- // }
- //
- // [iSalesDB close_db:db];
- //}
- //
- //-(void)test_descrypt1
- //{
- // sqlite3 *db = [iSalesDB get_db];
- //
- // int result= [iSalesDB AddExFunction:db];
- //
- // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
- //
- // [iSalesDB execSql:sqlindex];
- ////
- //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
- //// sqlite3_stmt * statement;
- ////
- ////
- ////
- //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
- //// {
- ////
- ////
- //// while (sqlite3_step(statement) == SQLITE_ROW)
- //// {
- ////
- ////
- //// char *url = (char*)sqlite3_column_text(statement, 0);
- //// if(url==nil)
- //// url="";
- //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
- //// DebugLog(nsurl);
- ////
- ////
- ////
- ////
- //// }
- //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
- ////
- ////
- //// sqlite3_finalize(statement);
- //// }
- //
- // [iSalesDB close_db:db];
- //}
- - (void)applicationWillResignActive:(UIApplication *)application
- {
- // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
- // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
- }
- - (void)applicationDidEnterBackground:(UIApplication *)application
- {
- // [self download_offline:false checkdiskspace:false];
- //
- // // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
- // // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
- //#if defined(GOOGLE_ANALYTICS)
- // NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
- // self.forgroundDate = nil;
- //
- // [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
- //#endif
- }
- - (void)applicationWillEnterForeground:(UIApplication *)application
- {
- // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
- }
- - (void)applicationDidBecomeActive:(UIApplication *)application
- {
- // if(self.download_task!=nil)
- // [self download_offline:true checkdiskspace:false];
- // // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
- //
- // self.forgroundDate = [NSDate date];
- //
- //
- //#ifdef SCANNER_ORDER
- //
- // [ RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
- //
- // configure.autoRemoveFinish = YES;
- // }];
- //
- // if (!self.uploadManager) {
- // RASingleton.sharedInstance.uploadManager=[RAUploadManager sharedManager];
- // }
- //
- //#endif
- }
- #ifdef SCANNER_ORDER
- -(RAUploadManager *)uploadManager
- {
- [RAUploadManager configureUploadManager:^(RAUPloadManagerConfigure *configure) {
-
- configure.autoRemoveFinish = YES;
- }];
-
- if (!RASingleton.sharedInstance.uploadManager) {
- RASingleton.sharedInstance.uploadManager=[RAUploadManager sharedManager];
- }
- return RASingleton.sharedInstance.uploadManager;
- }
- #endif
- -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
- {
- DebugLog(@"======================================");
- DebugLog(@"===== MEMORY WORRING ! ==========");
- DebugLog(@"======================================");
- }
- - (void)applicationWillTerminate:(UIApplication *)application
- {
-
- #ifdef SCANNER_ORDER
- // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
- [self saveUploadTasks];
-
- #endif
- }
- -(void) Logout
- {
- // 由于之前使用dispatch_async(dispatch_get_main_queue(), ^{}) 在用户切换时登出后刷新SideMenu User仍然显示
- dispatch_main_async_safe(^{
- MainViewController * main_vc= (MainViewController*)self.main_vc;
- [main_vc logoutOrder];
- [main_vc logoutCart];
- [main_vc logoutWish];
- [main_vc logoutContact];
- [main_vc logoutCategory];
- [main_vc logoutDocuments];
- [main_vc logoutPortfolio];
-
- #ifdef RA_NOTIFICATION
- [ActiveViewController Notify:@"SearchViewController" Message:RA_NOTIFICATION_CLEAR_DATA];
- #endif
-
- [main_vc hideMenu];
- [main_vc switchToHome];
- RASingleton.sharedInstance.user = nil;
- RASingleton.sharedInstance.password=nil;
- self.user_icon=nil;
- self.user_type = USER_ROLE_UNKNOWN;
- self.bLogin = false;
- self.contact_id=nil;
- self.customerInfo = nil;
- self.order_code = nil;
-
- [self.recent_model removeAllObjects];
-
- [self SetMode:nil];
-
- #ifdef SCANNER_ORDER
- self.available_price_group = nil;
- [RADataProvider default_price_group];
- #endif
- });
-
- }
- -(void)setOrder_code:(NSString *)order_code
- {
- _order_code = order_code;
-
- if(order_code==nil)
- DebugLog(@"Clear order code");
- else
- DebugLog(@"New order code %@",order_code);
- }
- - (void)checkLogin:(BOOL)reloadCurVC {
-
- [((MainViewController *)self.main_vc) checklogin:reloadCurVC];
- }
- //disable apn
- //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
- //{
- // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
- // DebugLog(@"regisger success:%@",deviceToken);
- //
- // //注册成功,将deviceToken保存到应用服务器数据库中
- //}
- #pragma mark - background download
- -(bool)isdownloading:(NSString*) file
- {
- return true;
- }
- -(long long)getcurrentLength:(int) taskidx
- {
-
- int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
- return position;
- }
- //-(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
- //{
- // //操作有两种,start stop;
- // //结果有四种, wait , downloading, pause, finish
- //
- // dispatch_async(dispatch_get_main_queue(), ^{
- // // debug;
- //// NSString* file_name=[url lastPathComponent];
- // //暂停<->开始转换
- //
- // // bool isdownloading = [self isdownloading:file_name];
- // if (start)
- // {//开始下载
- //
- //
- //
- //
- //
- //
- // DebugLog(@"%d start",taskidx);
- //
- // self.current_task=taskidx;
- //
- //
- //
- // NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
- //
- // // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
- // //
- // //
- // // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
- // //
- // // //设置请求头(GET)
- // // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
- // // [request setValue:range forHTTPHeaderField:@"Range"];
- // //
- // // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
- //
- //
- // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
- //
- // //设置请求头(GET)
- // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
- // [request setValue:range forHTTPHeaderField:@"Range"];
- //
- //
- // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
- //
- // }else{ //暂停
- // DebugLog(@"%d pause",taskidx);
- // [self.connection cancel];
- // self.connection = nil;
- // }
- // });
- //}
- -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order params:(NSMutableDictionary*) add_params
- {
-
- assert(add_params[@"user"]!=nil);
- assert(add_params[@"password"]!=nil);
- // assert(add_params[@"contact_id"]!=nil);
- [self add_downloadlog:@"Begin sync, please wait."];
- [self add_downloadlog:@"Prepare upload data."];
- // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
- NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order params:add_params];
-
- NSString* upfile=upjson[@"file"];
-
- {
- NSData* data = [NSData dataWithContentsOfFile: upfile];
- // UIApplication * app = [UIApplication sharedApplication];
- // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
-
- [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
-
- NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
-
- if(add_params[@"user"]!=nil)
- [params setValue:add_params[@"user"] forKey:@"user"];
- // if(appDelegate.contact_id!=nil)
- // [params setValue:appDelegate.contact_id forKey:@"contactId"];
- if(add_params[@"password"]!=nil)
- [params setValue:add_params[@"password"] forKey:@"password"];
-
-
- #if TARGET_IPHONE_SIMULATOR//模拟器
- [params setValue:@"simulator_uuid" forKey:@"idfv"];
- #elif TARGET_OS_IPHONE//真机
- UIDevice * dev = [UIDevice currentDevice];
- NSUUID* uuid =dev.identifierForVendor;
- [params setValue:uuid.UUIDString forKey:@"idfv"];
- #endif
- __weak typeof(self) weakSelf = self;
- [NetworkUtils upload:data FileName:[upfile lastPathComponent] Params:params ToHost:URL_UPLOAD_OFFLINE Result:^(NSMutableDictionary *json) {
-
- if([[json valueForKey:@"result"] intValue]==2)
- {
-
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // 清理数据库要放入线程中执行
- NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
- if (out_of_stock_ids) {
-
- [RAUtils message_box:@"Warning" message:[NSString stringWithFormat:@"Below orders were not submitted because some models were out of stock. You can check from order history under online mode.\n %@",out_of_stock_ids] completion:nil];
- }
-
- [weakSelf add_downloadlog:@"Upload successful."];
- // [iSalesDB disable_trigger]
- [iSalesDB disable_trigger];
- NSString* so_id=[RAConvertor arr2string:arr_order separator:@"," trim:true brackets:@"'"];
-
- [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
- [iSalesDB execSql:@"delete from wishlist"];
- [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
- [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
- [iSalesDB execSql:@"delete from offline_portfolio"];
- [iSalesDB execSql:@"delete from offline_pdf"];
- [OLDataProvider offline_clear_PDFCache];
-
- NSString* contactMap = json[@"contactMap"];
- if(contactMap.length>0)
- {
- NSDictionary* contactjson = [RAConvertor string2dict:contactMap];
- NSArray *keys= [contactjson allKeys];
- //遍历keys
- for(int i=0;i<[keys count];i++)
- {
- //得到当前key
- NSString *key=[keys objectAtIndex:i];
- //如果key不是pic,说明value是字符类型,比如name:Boris
- NSString* value = [contactjson valueForKey:key];
-
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
- [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
-
- }
- }
- // NSDictionary* contactjson= upjson[@"contact"];
- // NSDictionary* wishlistjson= upjson[@"wishlist"];
- // NSDictionary* orderjson= upjson[@"order"];
-
- // [iSalesDB enable_trigger]
- [iSalesDB enable_trigger];
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- [defaults removeObjectForKey:@"Forcedownload"];
- [defaults setBool:true forKey:@"Forcedownload"];
- [defaults synchronize];
-
- dispatch_async(dispatch_get_main_queue(), ^{
- //下载函数要从主线程调用
- [weakSelf download_offline:ver useInternalAddress:buseinternaladdress];
- });
- });
-
-
- }
- else
- {
- [weakSelf add_downloadlog:[json valueForKey:@"msg"]];
- [weakSelf add_downloadlog:@"Sync canceled."];
- [weakSelf.settingUI onSyncFinish];
- }
-
- } Progress:^(NSURLSessionTask *task, double progress) {
-
- } DecryptHandler:nil];
-
-
- }
-
-
-
- return;
- }
- -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
- {
- NSString *plistPath = [RAUtils get_config_path];
- NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
- if([config_list[@"NEED_FULLY_SYNC"] boolValue])
- {
- ver= nil;
- [self add_downloadlog:@"App required a fully sync."];
- }
-
-
- if(self.downloading)
- return;
-
- self.downloading=true;
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
-
- NSString* pvid = [defaults stringForKey:@"vid"] ;
-
-
-
- [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
- [RANetwork request_new_offline_ticket:ver useInternalAddress:false vid:pvid completionHandler:^(NSMutableDictionary *result) {
- NSMutableDictionary* json= result;
- if([json[@"result"] intValue]!=2)
- {
- [self add_downloadlog:@"Can not get offline data version, please try again later."];
- [self.settingUI onSyncFinish];
-
-
- // self.downloadlog=nil;
- self.downloading=false;
-
-
- return;
- }
- else
- {
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
- __block NSMutableDictionary* download_json=nil;
-
- // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
- NSString* downSerial=[json valueForKey:@"downSerial"];
-
- [defaults removeObjectForKey:@"downSerial"];
- [defaults setValue:downSerial forKey:@"downSerial"];
-
- [defaults synchronize];
-
- // sleep(3);
- //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
-
-
- // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // int count=0;
- // // __block bool preparing = true;
- // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
- // {
- // sleep(RETRY_DELAY);
- //
- //
- // count++;
- //// download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
- //
- // [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
- // download_json=result;
- // }];
- //
- //
- //
- //
- // }
-
- [RANetwork request_download_offline:downSerial completionHandler:^(NSMutableDictionary *result) {
- download_json=result;
-
- if([download_json[@"result"] intValue]!=RESULT_TRUE)
- {
- [self add_downloadlog:download_json[@"err_msg"]];
- [self add_downloadlog:@"Download Abort."];
- dispatch_async(dispatch_get_main_queue(), ^{
- // self.downloadlog=nil;
- self.downloading=false;
- [self.settingUI onSyncFinish];
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
-
- [defaults removeObjectForKey:@"Forcedownload"];
- [defaults setBool:true forKey:@"Forcedownload"];
- // NSString * downSerial = [defaults valueForKey:@"downSerial"];
- // [defaults removeObjectForKey:@"downSerial"];
- // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
- // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
- [defaults synchronize];
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- });
- return;
- }
- //服务器准备数据完毕,进入处理数据逻辑。
- if([download_json[@"request_count"] intValue]>=REQUEST_DOWNLOAD_RETRY_TIMES)
- {
- [self add_downloadlog:@"Can not get offline data version, please try again later."];
- dispatch_async(dispatch_get_main_queue(), ^{
- // self.downloadlog=nil;
- self.downloading=false;
- });
- dispatch_async(dispatch_get_main_queue(), ^{
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- });
- [self.settingUI onSyncFinish];
- return;
- //一直没取到json,出错处理
- }
- else
- {
- if([download_json[@"count"] intValue]==0)
- {
- //没有找到更新包,当前是最新版本
- [self add_downloadlog:@"You are up-to-date!"];
- dispatch_async(dispatch_get_main_queue(), ^{
- // self.downloadlog=nil;
- self.downloading=false;
-
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
-
- [defaults removeObjectForKey:@"Forcedownload"];
- [defaults setBool:FALSE forKey:@"Forcedownload"];
- // NSString * downSerial = [defaults valueForKey:@"downSerial"];
- // [defaults removeObjectForKey:@"downSerial"];
- // [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
- // [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
- [defaults synchronize];
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- });
- // dispatch_async(dispatch_get_main_queue(), ^{
- //
- // });
- [self.settingUI onSyncFinish];
- return;
- }
- else
- {
- [self add_downloadlog:@"Find a new version, downloading..."];
- self.download_task = [download_json mutableCopy];
- // self.download_task[@"abcdef"]=@"abcdef";
- long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
- [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
- [self download_offline:true checkdiskspace:true];
- return;
- }
-
- }
- }];
-
- }
-
- }];
- // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- //
- //
- //
- //
- // NSMutableDictionary* json=[[RANetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
- //
- //
- // if([json[@"result"] intValue]!=2)
- // {
- // [self add_downloadlog:@"Can not get offline data version, please try again later."];
- // [self.settingUI onSyncFinish];
- // dispatch_async(dispatch_get_main_queue(), ^{
- // // self.downloadlog=nil;
- // self.downloading=false;
- // });
- // return;
- // }
- //
- //
- // dispatch_async(dispatch_get_main_queue(), ^{
- // [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
- // });
- //
- //
- // NSMutableDictionary* download_json=nil;
- //
- // // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
- // NSString* downSerial=[json valueForKey:@"downSerial"];
- //
- // [defaults removeObjectForKey:@"downSerial"];
- // [defaults setValue:downSerial forKey:@"downSerial"];
- //
- // [defaults synchronize];
- //
- // // sleep(3);
- // //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
- //
- //
- // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- // int count=0;
- // // __block bool preparing = true;
- // while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
- // {
- // sleep(RETRY_DELAY);
- //
- //
- // count++;
- // download_json=[[RANetwork download_Offline:downSerial] mutableCopy];
- //
- //
- //
- //
- // }
- //
- // //服务器准备数据完毕,进入处理数据逻辑。
- // if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
- // {
- // [self add_downloadlog:@"Can not get offline data version, please try again later."];
- // dispatch_async(dispatch_get_main_queue(), ^{
- // // self.downloadlog=nil;
- // self.downloading=false;
- // });
- // dispatch_async(dispatch_get_main_queue(), ^{
- // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- // });
- // [self.settingUI onSyncFinish];
- // return;
- // //一直没取到json,出错处理
- // }
- // else
- // {
- // if([download_json[@"count"] intValue]==0)
- // {
- // //没有找到更新包,当前是最新版本
- // [self add_downloadlog:@"You are up-to-date!"];
- // dispatch_async(dispatch_get_main_queue(), ^{
- // // self.downloadlog=nil;
- // self.downloading=false;
- // });
- // dispatch_async(dispatch_get_main_queue(), ^{
- // [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- // });
- // [self.settingUI onSyncFinish];
- // return;
- // }
- // else
- // {
- // [self add_downloadlog:@"Find a new version, downloading..."];
- // self.download_task = [download_json mutableCopy];
- // // self.download_task[@"abcdef"]=@"abcdef";
- // long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
- // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
- // [self download_offline:true checkdiskspace:true];
- // return;
- // }
- //
- // }
- //
- // });
- }
- #ifdef SCANNER_ORDER
- //- (NSString *)price0_name
- //{
- // if(_price0_name.length==0)
- // {
- // return @"DDP";
- // }
- // else
- // return _price0_name;
- //}
- //- (NSString *)price1_name
- //{
- // if(_price1_name.length==0)
- // {
- // return @"Unit Price";
- // }
- // else
- // return _price1_name;
- //}
- //- (NSString *)price2_name
- //{
- // if(_price2_name.length==0)
- // {
- // return @"Special";
- // }
- // else
- // return _price2_name;
- //}
- //- (NSString *)price3_name
- //{
- // if(_price3_name.length==0)
- // {
- // return @"Net Price";
- // }
- // else
- // return _price3_name;
- //}
- #endif
- -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
- {
-
-
-
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- bool forcedownload = [defaults boolForKey:@"Forcedownload"];
-
- if(forcedownload|| ver==nil)
- {
- [self download_offline:ver useInternalAddress:buseinternaladdress];
- SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
- syncVC.action_string=@"Download";
- UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
-
-
- navi.modalInPresentation=true;
-
-
- // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
- navi.modalInPresentation = true;
- navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
- [parent presentViewController:navi animated:YES completion:^{
-
- // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
-
- DebugLog(@"about present.........");
-
- // self.btop = false;
- // <#code#>
- }];
-
- }
- else
- {
- NSArray* arr_order=nil;
- arr_order=[OLDataProvider enumOfflineOrder];
-
- NSMutableDictionary* add_params=[NSMutableDictionary new];
- add_params[@"user"]=RASingleton.sharedInstance.user;
- add_params[@"password"]=RASingleton.sharedInstance.password;
- add_params[@"contact_id"]=self.contact_id;
- [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order params:add_params];
- SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
- syncVC.action_string=@"Download";
- UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
- navi.modalInPresentation=true;
- navi.modalPresentationStyle = UIModalPresentationFormSheet;//有三种状态,自己看看是哪种
- [parent presentViewController:navi animated:YES completion:^{
-
- // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
-
- DebugLog(@"about present.........");
-
- // self.btop = false;
- // <#code#>
- }];
- // }
-
- }
-
-
-
-
-
-
-
- }
- -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
- {
-
-
- [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
- if(start)
- {
- dispatch_async(dispatch_get_main_queue(), ^{
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
- });
-
- long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
- // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
- long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
- long long needsize = size+500;
- if(needsize>freespace &&checkdiskspace)
- {
- //size not enough.
- NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
-
- [self add_downloadlog:space];
- [self.settingUI onSyncFinish];
-
-
- return ;
- }
-
- NSString* temp = NSTemporaryDirectory();
-
-
- NSString * ver = self.download_task[@"ver"];
-
- NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
-
- //创建版本临时目录
- NSFileManager* fileManager = [NSFileManager defaultManager];
- BOOL bdir=YES;
- if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
- {
-
- NSError *error = nil;
- bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create temp folder failed");
-
- // if(bsuccess)
- // {
- // sqlite3 *db = [self get_db];
- //
- // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
- // [iSalesDB close_db:db];
- // }
- }
-
- NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
-
- NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
- if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
- {
-
- NSError *error = nil;
- bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create cache folder failed");
-
- }
-
-
- NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
-
- NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
- // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
- // {
- //
- // NSError *error = nil;
- // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
- //
- // if(!bsuccess)
- // DebugLog(@"Create resource folder failed");
- //
- // }
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
- NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
-
- NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
- // tempdb=[documents stringByAppendingPathComponent:DBNAME];
- NSError *error = nil;
- bdir=NO;
- if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
- {
- // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
-
- if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
- {
- DebugLog(@"copy database failed");
- }
- }
- bdir=YES;
- error=nil;
- int count = [[self.download_task valueForKey:@"count"] intValue];
- bool alldone=true;
- bool trouble=false;
- bool response = false;
- for (int i = 0;i<count;i++)
- {
- NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
- NSString* url = [itemjson valueForKey:@"url"];
- NSString* type = [itemjson valueForKey:@"type"];
-
- {
- #ifdef DEBUG
- //调试模式下跳过下载图片
- if([type isEqualToString:@"img"])
- {
- itemjson[@"status"]=@"finish";
- continue;
- }
- #endif
- }
-
- NSString* status = itemjson[@"status"];
- //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
- if(! [status isEqualToString:@"finish"])
- {
-
- if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
- {
- // [self handle_download:url start:start type:type taskid:i];
- [self handle_download1:url start:start type:type taskid:i];
- alldone=false;
- break;
- }
- else
- {
- alldone=false;
- trouble=true;
- response = [itemjson[@"response"] boolValue];
- break;
- }
- }
-
- }
- if(trouble)
- {
- NSString* msg =@"offline sync got some trouble, sync canceled.";
- if(response==false)
- {
- msg=@"Cannot connect to server, please check your network.";
- }
- [self add_downloadlog:msg];
- dispatch_async(dispatch_get_main_queue(), ^{
- // self.downloadlog=nil;
- self.downloading=false;
- });
- [self.settingUI onSyncFinish];
- }
- else if(alldone)
- {
-
- [self add_downloadlog:@"Finalizing download..."];
- //全部下载完成;
- //写入当前版本
-
-
- NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
- [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
- NSString* lastsync = [formatter stringFromDate:[NSDate date]];
-
-
-
- NSString* ver= self.download_task[@"ver"];
-
-
-
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *cachefolder = [paths objectAtIndex:0];
- NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
- //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
-
- if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
- {
- DebugLog(@"move image folder failed");
- [self add_downloadlog:@"move image folder failed"];
- trouble=true;
- }
- else
- {
- DebugLog(@"move image folder successful");
- }
- error=nil;
-
-
- // copy temp db to cache.
- if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
- {
-
- if(![fileManager removeItemAtPath:database_path error:nil])
- {
- DebugLog(@"delete database failed");
- }
- else
- {
- if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
- {
- DebugLog(@"copy database failed");
- [self add_downloadlog:@"copy database failed"];
- trouble=true;
-
- }
- else{
- //debug
- // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
- [fileManager removeItemAtPath:tempdb error:nil];
- // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
- }
- }
- }
- else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
- {
- DebugLog(@"copy database failed");
- //debug;
- // BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
-
- [fileManager removeItemAtPath:tempdb error:nil];
- [self add_downloadlog:@"copy database failed"];
- trouble=true;
- }
-
- // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
- // {
- // DebugLog(@"move db file failed");
- // }
- // else
- // {
- // DebugLog(@"move db file successful");
- // }
- error=nil;
- if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
- {
- DebugLog(@"move data folder failed");
- [self add_downloadlog:@"move data folder failed"];
- trouble=true;
- }
- else
- {
- DebugLog(@"move data folder successful");
- }
-
-
- dispatch_async(dispatch_get_main_queue(), ^{
- [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
- });
-
-
- if(trouble)
- {
- [self add_downloadlog:@"offline sync failed."];
- // 尚缺更新失败还原逻辑。
- }
- else
- {
- [self add_downloadlog:@"offline sync complete."];
-
-
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- [defaults removeObjectForKey:@"OfflineVer"];
- [defaults setValue:ver forKey:@"OfflineVer"];
- [defaults removeObjectForKey:@"LastSync"];
- [defaults setValue:lastsync forKey:@"LastSync"];
- [defaults removeObjectForKey:@"vid"];
- [defaults setValue:self.vid forKey:@"vid"];
- [defaults removeObjectForKey:@"Forcedownload"];
- NSString * downSerial = [defaults valueForKey:@"downSerial"];
- [defaults removeObjectForKey:@"downSerial"];
- [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
- [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
- [defaults synchronize];
-
- NSString *plistPath = [RAUtils get_config_path];
- NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
- if([config_list[@"NEED_FULLY_SYNC"] boolValue])
- {
- config_list[@"NEED_FULLY_SYNC"] = @"false";
- [config_list writeToFile:plistPath atomically:YES];
- }
-
-
- [RANetwork request_complete_offline_ticket:downSerial completionHandler:^(NSMutableDictionary *result) {
-
- }];
-
- // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
- //
- //
- // //debug
- //// NSDictionary* editor_json = [RANetwork finish_download_Offline:downSerial];
- // [RANetwork finish_download_Offline:downSerial];
- //
- //
- // });
- }
-
- dispatch_async(dispatch_get_main_queue(), ^{
- // self.downloadlog=nil;
- self.downloading=false;
- self.download_task=nil;
- self.vid=nil;
-
-
- [self.settingUI onSyncFinish];
- });
- }
- }
- else
- {
- int count = [[self.download_task valueForKey:@"count"] intValue];
- for (int i = 0;i<count;i++)
- {
- NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
- NSString* url = [itemjson valueForKey:@"url"];
- NSString* type = [itemjson valueForKey:@"type"];
-
- NSString* status = itemjson[@"status"];
- //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
- if(! [status isEqualToString:@"finish"])
- {
-
- if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
- {
- // [self handle_download:url start:start type:type taskid:i];
- [self handle_download1:url start:start type:type taskid:i];
- break;
- }
-
- }
-
- }
- dispatch_async(dispatch_get_main_queue(), ^{
- self.downloading=false;
- });
- }
- }
- -(void) add_downloadlog:(NSString*) newtext
- {
- // if(!self.downloading)
- // return;
-
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString* date;
- NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
- [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
- date = [formatter stringFromDate:[NSDate date]];
-
-
- if(newtext.length<=0)
- return;
- NSString* text = self.downloadlog;
- if(text.length==0)
- text=@"";
- text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
- self.downloadlog = text;
-
-
- [self.settingUI onLogUpdate];
- });
- }
- -(int)unpack
- {
-
- //return;
-
- //DebugLog(_fileName);
- ///Users/Ray/Library/Developer/CoreSimulator/Devices/0852B217-599B-41C2-95BA-4755B02B7FA0/data/Containers/Data/Application/FC6AC5D0-2ADF-4A3B-935D-059078622031/Library/Caches/apache-tomcat-8.0.22.zip
- //文件路径
- // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
- NSString* temp = NSTemporaryDirectory();
-
- NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
-
- [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
-
- NSString * ver = self.download_task[@"ver"];
- NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
-
-
- NSString *zipFile = [temp stringByAppendingPathComponent:location];
- ZipArchive* zip = [[ZipArchive alloc] init];
-
- // filename stringByDeletingPathExtension
- // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- // NSString *cachefolder = [paths objectAtIndex:0];
-
- NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
-
- NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
- //
- // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
- //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
- // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
-
- DebugLog(@"path: %@",unZipTo);
- if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
- BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
- if( NO==result )
- {
- // int aaa=0;
- //解压失败
- long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
- if(freespace<=10)
- {
- return UNZIP_NO_SPACE;
- }
- [zip UnzipCloseFile];
- //文件损坏,删除文件重试
-
-
- NSFileManager* fileManager=[NSFileManager defaultManager];
- //debug
- // BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
- [fileManager removeItemAtPath:zipFile error:nil];
- [fileManager removeItemAtPath:unZipTo error:nil];
-
-
-
- return UNZIP_FILE_DAMAGE;
-
-
-
- }
- else
- {
- [zip UnzipCloseFile];
-
- [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
- NSFileManager *fileManager = [NSFileManager defaultManager];
- [fileManager removeItemAtPath:zipFile error:nil];
- return UNZIP_SUCCESS;
- //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
-
-
- }
- //[zip UnzipCloseFile];
- }
- else
- {
- //打开文件失败,通常是文件路径有问题或密码错误。
-
- return UNZIP_OPEN_FAILED;
- // NSFileManager *fileManager = [NSFileManager defaultManager];
- // [fileManager removeItemAtPath:zipFile error:nil];
- }
- // [zip release];
- }
- #pragma mark - NSURLConnectionDelegate
- -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
-
-
- DebugLog(@"%d error message:%@",self.current_task,error);
-
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
-
-
-
-
-
-
- // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
- currenttask[@"status"] = @"pause";
- int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
-
- [self download_offline:true checkdiskspace:false];
- }
- #pragma mark - NSURLConnectionDataDelegate
- /**
- *请求失败
- */
- /**
- *接收到服务器的响应
- */
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
-
- NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
-
- if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
-
-
- DebugLog(@"%d begin",self.current_task);
-
- long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
-
-
- //获取下载文件大小
- // self.fileLength = response.expectedContentLength;
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
- //获取文件名
- //self.fileName = response.suggestedFilename;
-
- currenttask[@"fileName"] = response.suggestedFilename;
- currenttask[@"response"] = @"true";
- [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- //文件路径
- NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
-
- NSString * ver = self.download_task[@"ver"];
- NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
- NSString *filePath = [temp stringByAppendingPathComponent:location];
- DebugLog(@"save to: %@",filePath);
-
- if (position>0) {
- //不需要创建文件;
- //创建一个用来写数据的文件句柄
- self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
- return;
- }
- // 第一次获取的才是文件正确大小
- currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
- //创建一个空的文件到沙盒
- NSFileManager *fileManager = [NSFileManager defaultManager];
- [fileManager createFileAtPath:filePath contents:nil attributes:nil];
-
- //创建一个用来写数据的文件句柄
- self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
- }else{
-
- //debug 这里缺少文件的情况还没处理
-
- [self.connection cancel];
- self.connection = nil;
- DebugLog(@"该文件不存在");
- NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
-
- [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
- [self add_downloadlog:str_status];
- }
-
- }
- /**
- *接收到服务器返回的数据(可能被调用多次)
- */
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
-
-
-
- //移动到文件末尾
- [self.fileHandle seekToEndOfFile];
-
- //写入数据到文件
- [self.fileHandle writeData:data];
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
- long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
- position += data.length;
- currenttask[@"position"] = [NSNumber numberWithLongLong:position];
-
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- //更新画面中的进度
- int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
-
-
-
-
-
- double progress = (double)position/fileLength;
-
- self.file_progress = progress;
- [self.settingUI onProgressUpdate];
- }
- /**
- *服务器返回数据完了
- */
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
-
-
- [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
-
- DebugLog(@"%d finish",self.current_task);
- currenttask[@"position"] = [NSNumber numberWithLongLong:0];
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- int result=[self unpack];
- NSString* temp = NSTemporaryDirectory();
-
- NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
-
-
-
- NSString * ver = self.download_task[@"ver"];
-
- NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
-
- NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
-
- switch (result) {
- case UNZIP_FILE_DAMAGE:
- {
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
- currenttask[@"status"] = @"pause";
- int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
- break;
- }
- case UNZIP_SUCCESS:
- {
- NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
-
- if([type isEqualToString:@"img"])
- {
-
- NSString* parent_path = self.download_task[@"path"];
- if(parent_path.length==0)
- parent_path=@"";
- parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
- parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
- NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
-
-
-
- NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
-
- BOOL bdir=YES;
- NSError *error = nil;
- if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
- {
-
- bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create temp folder failed");
- }
-
- error=nil;
- // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
- // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
-
- // NSError *error = nil;
- // NSURL* uf=[NSURL fileURLWithPath:imagecache];
- // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
- // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
- // backupItemName:backup
- // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
- // resultingItemURL:nil error:&error])
- if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
- // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
- {
- DebugLog(@"move image folder failed");
- }
- else
- {
- currenttask[@"status"] = @"finish";
- DebugLog(@"move image folder successful");
- }
-
- }
- else if([type isEqualToString:@"sql"])
- {
- // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
- NSString * ver = self.download_task[@"ver"];
- NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
- tempdb=[temp stringByAppendingPathComponent:tempdb];
- sqlite3* tdb=[iSalesDB get_db_at:tempdb];
-
-
- [self add_downloadlog:@"updating local database..."];
-
-
- @try {
- char *errmsg=NULL;
- // [iSalesDB disable_trigger]
- [iSalesDB disable_trigger];
-
- if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
- {
-
- sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;drop trigger if exists offline_pdf;", NULL, NULL, &errmsg);
-
- sqlite3_free(errmsg);
- DebugLog(@"开启事务");
- NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
-
- NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
- int count = [orderjson[@"count"] intValue];
- for(int i=0;i<count;i++)
- {
- NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
- NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
- NSError *error = nil;
- NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
- //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
-
-
-
-
- if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
- {
- //throw exception;
- if(errmsg==nil)
- errmsg="Unknown error.";
- NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
- [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
- }
-
- sqlite3_free(errmsg);
- }
-
-
- sqlite3_exec(tdb, "CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
- }
- //提交事务
- if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
-
- DebugLog(@"提交事务");
-
- sqlite3_free(errmsg);
- }
-
- [self add_downloadlog:@"updating local database successful"];
- currenttask[@"status"] = @"finish";
-
- }
-
-
- @catch (NSException *exception) {
- char *errmsg=NULL;
- [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
- [self add_downloadlog:@"updating local database failed rollback..."];
- if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
- DebugLog(@"回滚事务");
-
-
-
-
-
-
- }
- else
- {
- [self add_downloadlog:@"rollback failed."];
- }
-
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
- currenttask[@"status"] = @"pause";
- //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
- //break;
- }
- @finally {
-
- // [iSalesDB enable_trigger]
- [iSalesDB enable_trigger];
- sqlite3_close(tdb);
- // [iSalesDB close_db:tdb];
- // [self SelectData];
- }
-
- }
- else if([type isEqualToString:@"script"])
- {
- currenttask[@"status"] = @"finish";
- }
- else if([type isEqualToString:@"resource"])
- {
- currenttask[@"status"] = @"finish";
- }
- // debug
- // int c=self.current_task+1;
- // double t=[ self.download_task[@"count"] doubleValue];
- double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
- self.overall_progress = oprogress;
- [self.settingUI onProgressUpdate];
- break;
- }
- case UNZIP_NO_SPACE:
- {
- [self add_downloadlog:@"Disk space not enough."];
-
- break;
- }
- case UNZIP_OPEN_FAILED:
- {
- [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
- break;
- }
- default:
- break;
- }
- [self download_offline:true checkdiskspace:false];
- }
- -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
- {
- RAPDFViewController *ViewController = [[UIStoryboard storyboardWithName:@"wkweb" bundle:nil] instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
- ViewController.url = url;
- ViewController.canSave = false;
-
-
-
- ViewController.mail_content = content;
-
-
- if(soid==nil)
- soid =@"";
-
- if(company==nil)
- company =@"";
-
-
- ViewController.save_name =soid;
-
-
-
-
- NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
- if(send_to.length>0)
- {
- arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
- // customer_email compo
- // [send_to addObject:customer_email];
- }
- ViewController.mail_to = arrsend_to;
-
- #if defined(BUILD_NPD) || defined(BUILD_USAI)|| defined (BUILD_CONTRAST)
-
- NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];//[arr_subject componentsJoinedByString:@" : "];
-
- if (self.user_type == USER_ROLE_CUSTOMER && ![RASingleton sharedInstance].currentOrderIsMerged) {
- NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
- subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
- }
- #else
-
- NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,COMPANY_NAME];
-
- #endif
-
- ViewController.mail_subject = subject;
-
-
-
- // NSString* subject;
- // if (company.length==0) {
-
- // NSString* cur_time =[RAUtils current_date];
- // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
-
- // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
- // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
- //
- //
- // NSMutableArray* send_to = [[NSMutableArray alloc]init];
- // if(customer_email.length>0)
- // {
- // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
- // // customer_email compo
- // // [send_to addObject:customer_email];
- // }
- // ViewController.mail_to = send_to;
-
- // }
- // else
- // {
- // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
- // }
- // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
- // ViewController.mail_subject = subject;
- ViewController.autoPrint=true;
- ViewController.hidenavi = false;
- [self.main_vc.navigationController pushViewController:ViewController animated:YES];
- // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
-
-
- }
- //-(void) addScannerReceiver:(NSString*)classname
- //{
- // [self.arr_scannerReceiver addObject:classname];
- //}
- #ifdef USE_MFI_SCANNER
- -(void) setScannerDelegate:(id<ScanApiHelperDelegate>)delegate
- {
- [ScanApi setDelegate:delegate];
- }
- #endif
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
-
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- // 蓝牙扫描枪
- #ifdef USE_BLE_SCANNER
-
- self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
- _cbReady = false;
- _nDevices = [[NSMutableArray alloc]init];
- _nServices = [[NSMutableArray alloc]init];
- _nCharacteristics = [[NSMutableArray alloc]init];
-
-
-
-
- self.bAutoConnect=[defaults boolForKey:@"BLE_AutoReconnect"];
- self.bAppBTOn=[defaults boolForKey:@"BLE_Enable"];
- if(self.bAutoConnect)
- {
- self.strDeviceName = [defaults valueForKey:@"BLE_Name"];
- self.strDeviceUUID = [defaults valueForKey:@"BLE_UUID"];
- }
- #endif
-
- // [defaults removeObjectForKey:@"BLE_AutoReconnect"];
-
-
- #ifdef SCANNER_ORDER
- //审核时连接测试数据库
-
- // NSDate *cdate= [NSDate date];
- // NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
- // [dateFormatter setDateFormat:@"yyyy-MM-dd"];
- //
- //NSDate * ddate =[dateFormatter dateFromString:@"2022-07-08"];
- //
- //// bool review=[cdate earlierDate:ddate];
- // NSTimeInterval secondsInterval= [cdate timeIntervalSinceDate:ddate];
- // int sec =secondsInterval;
-
-
- bool rtime = [RADataProvider scanRtime];
- NSDictionary *addressDic = [[NSUserDefaults standardUserDefaults] valueForKey:@"ScanAddress"];
- if(rtime && !addressDic)
- {
-
- NSUInteger selectedIndex = 1;
-
- // 保存信息
-
- NSString *name = @"HMLG";
- NSString *show_name = @"FREMONT, CA";
- NSString *internalAddr =@"https://erp.homelegance.com/" ;
- int price_index = 0;
- // NSString *externalAddr = weakself.externalTextField.text;
- NSMutableDictionary *addressDic = [NSMutableDictionary dictionary];
- if (internalAddr.length) {
- [addressDic setObject:internalAddr forKey:@"serverAddress"];
- }
- // if (externalAddr.length) {
- // [addressDic setObject:externalAddr forKey:@"externalAddress"];
- // }
- if (name.length) {
- [addressDic setObject:name forKey:@"name"];
- }
- if (show_name.length) {
- [addressDic setObject:show_name forKey:@"show_name"];
- }
- addressDic[@"has_erp_site"] = @(true);
- [addressDic setObject:@(price_index) forKey:@"price_index"];
- [addressDic setObject:@(selectedIndex) forKey:@"selectedIndex"];
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- [userDefaults setValue:addressDic forKey:@"ScanAddress"];
- [userDefaults synchronize];
-
-
- }
-
-
-
- self.compressFile = [[RAUPloadManagerConfigure alloc] init].compressImage;
-
- #endif
-
-
- //#ifdef OFFLINE_ORDER
- //
- //#endif
-
-
- self.window.backgroundColor = [UIColor whiteColor];
-
- // [RAUtils expression_varable:nil regex:nil];
- // self.disable_trigger = false;
- [iSalesDB enable_trigger];
- [self initialExceptionHandler];
- [self becomeObserver];
- #ifdef GOOGLE_ANALYTICS
- [self setUpGoogleAnalytics];
- #endif
-
- [DefaultAppearance init_appearance];
-
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- NSString *cachefolder = [paths objectAtIndex:0];
-
- NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
- // upfolder = [upfolder stringByAppendingPathComponent:serial];
-
- NSFileManager* fileManager = [NSFileManager defaultManager];
- BOOL bdir=YES;
- if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
- {
-
- NSError *error = nil;
- bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create UPLOAD folder failed");
-
- }
-
- NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
-
- if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
- {
- NSError *error = nil;
- bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create PDF Cache folder failed");
-
- }
-
-
- // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
- //
- // DebugLog(@"文件已经存在了");
- //
- // }
-
-
-
-
-
- // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
- // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
- //
- //
- // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
- // NSString *documents = [paths objectAtIndex:0];
- // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
- //
- //
- // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
- //
- // DebugLog(@"文件已经存在了");
- //
- // }
- // else
- // {
- //
- //
- //
- // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
- //
- // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
- //
- // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
- //
- // [[NSFileManager defaultManager] createFileAtPath:dist_path
- //
- // contents:mainBundleFile
- //
- // attributes:nil];
- //
- // }
-
-
- self.recent_model = [[NSMutableDictionary alloc]init];
- // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
- self.offline_mode = offline;
- // Override point for customization after application launch.
-
- if ( [iSalesDB initializeDb]!=0)
- DebugLog(@"init db failed");
- // disable apn
- // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
- self.contact_id=nil;
-
- // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
- if([enable_cache isEqualToString:@"false"])
- self.bEnable_Cache = false;
- else
- self.bEnable_Cache = true;
-
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- RASingleton.sharedInstance.build =[infoDict objectForKey:@"CFBundleVersion"];
-
- //scanner
-
- _feedbackStack=[[NSMutableArray alloc]init];
-
- self.devices=[[NSMutableArray alloc]init];
-
- // change this to YES if you want SingleEntry to
- // confirm the decoded data
- self.doAppDataConfirmation=NO;
-
-
- #ifdef USE_MFI_SCANNER
-
- if(ScanApi==nil){
-
- ScanApi=[[ScanApiHelper alloc]init];
- [ScanApi setDelegate:self];
- self.enable_ScannerLog = true;
- self.api_Status= API_STOP;
-
-
-
- // UIApplication * app = [UIApplication sharedApplication];
- // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
- //
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
- if(autolaunch==true)
- [self enableScanner:autolaunch];
-
- }
- #else
- if(true){
-
-
- self.enable_ScannerLog = true;
- self.api_Status= API_STOP;
-
-
-
- // UIApplication * app = [UIApplication sharedApplication];
- // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
- //
-
- #ifdef USE_MFI_SCANNER
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
- if(autolaunch==true)
- {
-
- [self enableScanner:autolaunch];
-
- }
- #endif
-
- }
-
- #endif
-
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- [self handleErrorLog];
- });
-
- return YES;
- }
- #pragma mark - Feedback stack
- -(void)pushFeedback:(id<ScannerEventsFeedback>)feedback{
-
- long index =[_feedbackStack indexOfObject:feedback];
- if(index!=NSNotFound)
- {
- // if(index!=_feedbackStack.count-1)
- // {
- // [_feedbackStack exchangeObjectAtIndex:index withObjectAtIndex:_feedbackStack.count-1];
- // _eventsFeedback = feedback;
- // }
-
-
- }
- else
- {
- [_feedbackStack addObject:feedback];
-
- }
- _eventsFeedback = feedback;
- // if(_eventsFeedback != feedback){
- // if(_eventsFeedback!=nil){
- // [_feedbackStack addObject:_eventsFeedback];
- // }
- // _eventsFeedback=feedback;
- //// [self generateDeviceArrivals];
- // }
- }
- -(void)popFeedback:(id<ScannerEventsFeedback>)feedback{
-
- [_feedbackStack removeObject:feedback];
- if(_feedbackStack.count>0)
- _eventsFeedback = _feedbackStack[_feedbackStack.count-1];
- else
- _eventsFeedback = nil;
- // if(_eventsFeedback ==feedback){
- // if(_feedbackStack.count>0){
- // id<ScannerEventsFeedback> newDelegate=[_feedbackStack objectAtIndex:_feedbackStack.count-1];
- // [_feedbackStack removeLastObject];
- // _eventsFeedback = newDelegate;
- // // generate a device Arrival for each scanner we've already receive
- // // so that the new view can be aware of the connected scanners
- //// [self generateDeviceArrivals];
- // }
- // else{
- // _eventsFeedback=nil;
- // }
- // }
- }
- -(void)setFeedback:(id<ScannerEventsFeedback>)feedback
- {
- _eventsFeedback = feedback;
- }
- #pragma mark - ScanApiHelper complete delegates
- // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
- // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
- // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
- // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
- // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
- // callback received when the Get Symbology Status is completed
- #ifdef USE_MFI_SCANNER
- -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
- [self addlog:@"onGetSymbologyDpm:"];
-
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
- if(deviceInfo!=nil){
- ISktScanSymbology* symbology=[[scanObj Property]Symbology];
- if([symbology getStatus]==kSktScanSymbologyStatusDisable){
- [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
- }
- }
- }
- else{
- // an error message should be displayed here
- // indicating that the DPM symbology status cannot be retrieved
- }
- }
- // callback received when the Set Symbology Status is completed
- -(void)onSetSymbology:(ISktScanObject*)scanObj{
- [self addlog:@"onSetSymbology:"];
-
- SKTRESULT result=[[scanObj Msg]Result];
- if(!SKTSUCCESS(result)){
- // display an error message saying a symbology cannot be set
- }
- }
- /**
- *
- */
- -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
-
- [self addlog:@"onSetDataConfirmationMode:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
-
- [self addlog:@"DataConfirmation Mode OK"];
-
- }
- else{
- [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onDataConfirmation:(ISktScanObject*)scanObj{
- [self addlog:@"onDataConfirmation:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- [self addlog:@"Data Confirmed OK"];
- }
- else{
- [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
- [self addlog:@"onSetLocalDecodeAction:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- [self addlog:@"Local Decode Action OK"];
- }
- else{
- [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- ISktScanProperty* property=[scanObj Property];
-
- [self addlog:@"SoftScan status:"];
- if([property getByte]==kSktScanEnableSoftScan){
- [self addlog:@"SoftScan is ENABLED"];
- _softScannerEnabled=TRUE;
- }
- else{
- _softScannerEnabled=FALSE;
- [self addlog:@"SoftScan is DISABLED"];
- }
-
-
- }
- else{
- [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
- [self addlog:@"onSetSoftScanStatus:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- [self addlog:@"SoftScan set status success"];
- }
- else{
- [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onSetTrigger:(ISktScanObject*)scanObj{
- [self addlog:@"onSetTrigger:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result)){
- [self addlog:@"Trigger set success"];
- }
- else{
-
-
- [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
- }
- }
- /**
- *
- */
- -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
- [self addlog:@"onGetScanApiVersion:"];
- SKTRESULT result=[[scanObj Msg]Result];
- if(SKTSUCCESS(result))
- {
- ISktScanProperty*property=[scanObj Property];
- if([property getType]==kSktScanPropTypeVersion)
- {
- scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
- [[property Version]getMajor],
- [[property Version]getMiddle],
- [[property Version]getMinor],
- [[property Version]getBuild]];
- }
- }
- else{
- scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
- }
-
-
- [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
- }
- /**
- *
- */
- /**
- * called each time a device connects to the host
- * @param result contains the result of the connection
- * @param newDevice contains the device information
- */
- -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
- [self addlog:@"onDeviceArrival:"];
-
- [self updateDevicesList:deviceInfo Add:YES];
-
-
- {
- if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
- // _softScannerTriggerBtn.hidden=NO;
- _deviceInfoToTrigger=deviceInfo;
- }
- if(_doAppDataConfirmation==YES){
- // switch the comment between the 2 following lines for handling the
- // data confirmation beep from the scanner (local)
- // if none is set, the scanner will beep only once when SingleEntry actually
- // confirm the decoded data, otherwise the scanner will beep twice, one locally,
- // and one when SingleEntry will confirm the decoded data
- [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
-
- // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
- }
-
- // for demonstration only, let's make sure the DPM is enabled
- // first interrogate the scanner to see if it's already enabled
- // and in the onGetSymbologyDpm callback, if the DPM is not already set
- // then we send a Symbology property to enable it.
- [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
- }
-
-
- }
- /**
- * called each time a device disconnect from the host
- * @param deviceRemoved contains the device information
- */
- -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
-
- [self addlog:@"onDeviceRemoval:"];
- [self updateDevicesList:deviceRemoved Add:NO];
- if(_deviceInfoToTrigger==deviceRemoved){
- _deviceInfoToTrigger=nil;
- }
- if(_deviceInfoToTrigger==nil){
- // _softScannerTriggerBtn.hidden=YES;
- }
- }
- /**
- * called each time ScanAPI is reporting an error
- * @param result contains the error code
- */
- -(void) onError:(SKTRESULT) result{
- [self addlog:@"onError:"];
-
- [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
- [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
- #endif
- // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
-
- }
- /**
- * called each time ScanAPI receives decoded data from scanner
- * @param deviceInfo contains the device information from which
- * the data has been decoded
- * @param decodedData contains the decoded data information
- */
- -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
-
- [self addlog:@"onDecodedDataResult:"];
- //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
- if(SKTSUCCESS(result)){
-
-
- NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
- [_eventsFeedback onDecodedData:cleanString];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onDecodedData:cleanString];
- #endif
-
-
- //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
- [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
- if(_doAppDataConfirmation==YES){
- [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
- }
- }
- }
- -(void) test_onDecodedDataResult:(NSString*) value
- {
-
- [self addlog:@"onDecodedDataResult:"];
- //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
- if(true){
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
- [_eventsFeedback onDecodedData:value];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onDecodedData:value];
- #endif
-
-
- //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
- [self addlog:value];
- // if(_doAppDataConfirmation==YES){
- // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
- // }
- }
- }
- //-(void) didRotated
- //{
- //
- //}
- /**
- * called when ScanAPI initialization has been completed
- * @param result contains the initialization result
- */
- -(void) onScanApiInitializeComplete:(SKTRESULT) result{
-
- [self addlog:@"onScanApiInitializeComplete:"];
-
- if(SKTSUCCESS(result))
- {
- self.api_Status = API_START;
-
- NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
- [self addlog:strlog];
-
- // disable support SoftScan (Default, not really needed if it was never activated)
- [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
-
- // ask for ScanAPI version (not a requirement but always nice to know)
- [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
-
- // configure ScanAPI for doing App Data confirmation,
- // if TRUE then SingleEntry will confirm the decoded data
- if(_doAppDataConfirmation==YES){
- [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
- }
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Waiting for scanner..."];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onStatusChanged:@"Waiting for scanner..."];
- #endif
-
-
- self.Status_Text = @"Waiting for scanner...";
- // _Status.text=@"Waiting for scanner...";
- }
- else{
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
- #endif
-
- self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
- // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
- NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
- [self addlog:strlog];
- }
- }
- /**
- * called when ScanAPI has been terminated. This will be
- * the last message received from ScanAPI
- */
- -(void) onScanApiTerminated{
-
- [self addlog:@"onScanApiTerminated:"];
-
-
- [ScanApiConsumer invalidate];
- ScanApiConsumer= nil;
- [self addlog:@"ScanApiConsumer invalidate"];
-
- self.api_Status = API_STOP;
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Off"];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onStatusChanged:@"Off"];
- #endif
-
-
- self.Status_Text =@"Off";
- // _Status.text = @"Off";
-
- }
- /**
- * called when an error occurs during the retrieval
- * of a ScanObject from ScanAPI.
- * @param result contains the retrieval error code
- */
- -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
-
- [self addlog:@"onErrorRetrievingScanObject:"];
- [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
- //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onErrorInfo:)])){
- [_eventsFeedback onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
- #endif
-
- }
- #endif
- #pragma mark - Scaner
- -(void)onTimer: (NSTimer*)theTimer{
- if(theTimer==ScanApiConsumer){
-
- // [self addlog:@"ScanApi::doScanApiReceive:"];
-
-
-
-
- #ifdef USE_MFI_SCANNER
-
- [ScanApi doScanApiReceive];
- #endif
- }
- }
- -(void) addlog:(NSString*) newtext
- {
- if(!self.enable_ScannerLog)
- return;
-
- dispatch_async(dispatch_get_main_queue(), ^{
- NSString* date;
- NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
- [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
- date = [formatter stringFromDate:[NSDate date]];
-
-
- if(newtext.length<=0)
- return;
- NSString* text = self.log;
- if(text.length==0)
- text=@"";
- text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
- self.log = text;
-
-
- #ifdef RA_NOTIFICATION
- if((self->_eventsFeedback!=nil)&&([self->_eventsFeedback respondsToSelector:@selector(onLogUpdate)])){
- [self->_eventsFeedback onLogUpdate];
- }
- #else
-
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onLogUpdate];
- #endif
-
- });
- }
- #ifdef USE_MFI_SCANNER
- - (void)enableScanner:(bool)enable {
-
- [self addlog:@"Enable scanner:"];
-
- if(enable)
- {
- [self addlog:@"Enable"];
-
- self.api_Status = API_INIT;
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Initialize..."];
- }
- #else
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onStatusChanged:@"Initialize..."];
- #endif
-
-
- self.Status_Text = @"Initialize...";
- [ScanApi open];
- [self addlog:@"ScanApi open"];
-
- ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
- [self addlog:@"ScanApiConsumer init"];
-
- // [ScanApi close];
- // [self addlog:@"ScanApi opent"];
- }
- else
- {
- [self addlog:@"Disable"];
-
-
- // [ScanApiConsumer invalidate];
- // ScanApiConsumer= nil;
- // [self addlog:@"ScanApiConsumer invalidate"];
-
-
- self.api_Status = API_CLOSING;
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Stoping..."];
- }
- #else
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
-
- [avc onStatusChanged:@"Stoping..."];
- #endif
-
- self.Status_Text = @"Stoping...";
- [ScanApi close];
-
-
- [self addlog:@"ScanApi close"];
-
-
- }
- }
- #pragma mark - Device Info List management
- -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
-
- [self addlog:@"updateDevicesList:"];
-
- if(add==YES){
- [self.devices addObject:deviceInfo];
- }
- else{
- [self.devices removeObject:deviceInfo];
- }
-
- NSMutableString* temp=[[NSMutableString alloc]init];
- for (DeviceInfo* info in self.devices) {
- [temp appendString:[info getName]];
- [temp appendString:@"\n"];
- }
- if(self.devices.count>0)
- [temp appendString:@"ready to scan"];
- else
- [temp appendString:@"Waiting for Scanner..."];
-
-
- // _Status.text=temp ;
- [self addlog:temp];
-
- #ifdef RA_NOTIFICATION
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:temp];
- }
-
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
- [_eventsFeedback OnUpdateDevicesList];
- }
- #else
- ActiveViewController* avc=(ActiveViewController*)self.active_controller;
- [avc onStatusChanged:temp];
- [avc OnUpdateDevicesList];
- #endif
- self.Status_Text = temp;
-
- // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
- // [self.dev_table reloadData];
-
- }
- #endif
- #pragma mark - offline order
- -(void) backup_oc
- {
-
- }
- -(void) restore_oc
- {
-
- }
- #ifdef SCANNER_ORDER
- #pragma mark - upload manager
- - (void)saveUploadTasks {
-
- if(true)
- {
-
- if(self.uploadManager.arr_queue!=nil)
- {
-
- [self.uploadManager stopAllTasks];
-
-
- }
- [self.uploadManager saveTasks];
- return;
- }
- }
- - (NSMutableArray *)cachedUploadTasks {
- if (!RASingleton.sharedInstance.user) {
- return nil;
- }
- NSString *path = [[RAUtils appCacheDirectory] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_uploadTasks",RASingleton.sharedInstance.user]];
-
- NSFileManager *manager = [NSFileManager defaultManager];
- if ([manager fileExistsAtPath:path]) {
- NSMutableArray *arr = [NSMutableArray arrayWithContentsOfFile:path];
- [manager removeItemAtPath:path error:nil];
- return arr;
- }
-
- return nil;
- }
- #endif
- #ifdef USE_BLE_SCANNER
- #pragma mark - core bluetooth
- -(void) disconnectDevice
- {
- if(self.peripheral)
- { [self.manager cancelPeripheralConnection:self.peripheral];
- self.peripheral = nil;
- }
- [self setBLEAutoReconnect:false];
-
- if( self.bAppBTOn ==true)
- [self scanBLE];
- }
- -(void)setBLEAutoReconnect:(bool) bAutoReconnect
- {
- self.bAutoConnect = true;
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- [defaults removeObjectForKey:@"BLE_Name"];
- [defaults removeObjectForKey:@"BLE_UUID"];
- [defaults removeObjectForKey:@"BLE_AutoReconnect"];
- if(bAutoReconnect&&self.peripheral)
- {
-
-
-
- [defaults setValue:self.peripheral.name forKey: @"BLE_Name"];
- [defaults setValue:self.peripheral.identifier.UUIDString forKey: @"BLE_UUID"];
-
-
-
-
- }
- else
- {
- self.strDeviceName = nil;
- self.strDeviceUUID=nil;
- }
-
- [defaults setBool:bAutoReconnect forKey:@"BLE_AutoReconnect"];
-
- [defaults synchronize];
- }
- -(void) enableBLE:(bool) bEnable
- {
- self.bAppBTOn =bEnable;
-
- NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
- [defaults removeObjectForKey:@"BLE_Enable"];
- [defaults setBool:self.bAppBTOn forKey:@"BLE_Enable"];
- [defaults synchronize];
- if(bEnable)
- [self scanBLE];
- else
- [self stopScanBLE];
- }
- -(void) scanBLE
- {
-
- switch (self.manager.state) {
- case CBManagerStatePoweredOn:
- {
- [self updateLog:@"Scanning..."];
-
- [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
- // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
- }
- break;
- case CBManagerStatePoweredOff:
- [self updateLog:@"Please turn on bluetooth。"];
- break;
- default:
- break;
- }
- }
- -(void) stopScanBLE
- {
- // self.bAppBTOn = false;
- [self.manager stopScan];
-
- if(self.self.peripheral)
- [self.manager cancelPeripheralConnection:self.peripheral];
- self.nDevices = [NSMutableArray new];
- self.peripheral = nil;
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
- [_eventsFeedback OnUpdateDevicesList];
- }
-
- }
- //检查蓝牙状态
- - (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
- switch (central.state) {
- case CBManagerStatePoweredOn:
- {
- [self updateLog:@"Bluetooth on."];
- self.bBTAuthorize = true;
- if(self.bAppBTOn)
- {
- [_manager scanForPeripheralsWithServices:/*@[[CBUUID UUIDWithString:@"FFF0"]]*/nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @false}];
- }
-
- // [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @true}];
- }
- break;
- case CBManagerStatePoweredOff:
- [self updateLog:@"Bluetooth off."];
- self.bBTAuthorize = true;
- break;
-
- case CBManagerStateUnauthorized:
- //蓝牙未授权
-
- // app一定未授权,蓝牙是否开启不知
- [self updateLog:@"Bluetooth Unauthorized."];
-
- self.bBTAuthorize = false;
-
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Unauthorized"];
- }
- break;
- default:
- break;
- }
- }
- -(void)updateLog:(NSString*) log
- {
- // DebugLog(log);
- //
- // self.strBTLog=[self.strBTLog stringByAppendingString:[log stringByAppendingString:@"\n"]];
- [self addlog:log];
- }
- -(NSString *) NSDataToHex:(NSData *)data {
- // NSUInteger i, len;
- // unsigned char *buf, *bytes;
- //
- // len = data.length;
- // bytes = (unsigned char*)data.bytes;
- // buf = malloc(len*2);
- //
- // for (i=0; i<len; i++) {
- // buf[i*2] = itoh((bytes[i] >> 4) & 0xF);
- // buf[i*2+1] = itoh(bytes[i] & 0xF);
- // }
- //
- // return [[NSString alloc] initWithBytesNoCopy:buf
- // length:len*2
- // encoding:NSASCIIStringEncoding
- // freeWhenDone:YES];
-
-
-
- NSUInteger dataLength = [data length];
- NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
- const unsigned char *dataBytes = [data bytes];
- for (NSInteger idx = 0; idx < dataLength; ++idx) {
- [string appendFormat:@"%02x", dataBytes[idx]];
- }
- return string;
- }
- //查到外设后,停止扫描,连接设备
- -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
- {
- // DebugLog(@"didDiscoverPeripheral");
-
- NSArray* pservice = advertisementData[@"kCBAdvDataServiceUUIDs"];
- if(pservice.count<=0)
- return;
- if(peripheral.name.length<=0)
- return;
- // _peripheral = peripheral;
- // [_manager connectPeripheral:_peripheral options:nil];
- // [self.manager stopScan];
- // [_activity stopAnimating];
- BOOL replace = NO;
- // Match if we have this device from before
- for (int i=0; i < _nDevices.count; i++) {
- CBPeripheral *p = [_nDevices objectAtIndex:i];
- if ([p isEqual:peripheral]) {
- [_nDevices replaceObjectAtIndex:i withObject:peripheral];
- replace = YES;
- }
- }
- if (!replace) {
- [_nDevices addObject:peripheral];
- [self updateLog:[NSString stringWithFormat:@"Found device: %@ rssi: %@, UUID: %@ advertisementData: %@ ", peripheral, RSSI, peripheral.identifier, advertisementData]];
- // advertisementData[@"kCBAdvDataManufacturerData"];
- // NSString* a=[[NSString alloc] initWithData:advertisementData[@"kCBAdvDataManufacturerData"] encoding:NSASCIIStringEncoding];
- // NSString* b=[[NSString alloc] initWithData:advertisementData[@"kCBAdvDataManufacturerData"] encoding:NSUTF8StringEncoding];
- // NSString* d = [self NSDataToHex:advertisementData[@"kCBAdvDataManufacturerData"]];
- // int c=0;
- }
-
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(OnUpdateDevicesList)])){
- [_eventsFeedback OnUpdateDevicesList];
- }
-
- if(self.bAutoConnect&& [self.strDeviceUUID isEqualToString:peripheral.identifier.UUIDString])
- {
- self.peripheral = peripheral;
- NSString* log = [NSString stringWithFormat:@"Reconnect to device %@ ...", peripheral.name];
- [self updateLog:log];
- DebugLog(@"Retrying");
- [self.manager connectPeripheral:peripheral options:nil];
- }
-
- // if(peripheral.identifier == self.peripheral.identifier)
- // {
- // //重新连接
- // [_manager connectPeripheral:_peripheral options:nil];
- // }
-
- //[_bluetoothTable reloadData];
- }
- //连接外设成功,开始发现服务
- - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
- DebugLog(@"%@", [NSString stringWithFormat:@"成功连接 peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]);
- [self updateLog:[NSString stringWithFormat:@"Connect peripheral: %@ with UUID: %@",peripheral,peripheral.identifier]];
- [self.peripheral setDelegate:self];
- [self.peripheral discoverServices:nil];
-
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Connected"];
- }
- // [self updateLog:@"扫描服务"];
- }
- //连接外设失败
- -(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
- {
- DebugLog(@"%@",error);
- [self updateLog:@"Failed to connect device."];
- }
- - (void)peripheral:(CBPeripheral *)peripheral
- didReadRSSI:(NSNumber *)RSSI
- error:(NSError *)error
- {
- DebugLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);
- int rssi = abs([RSSI intValue]);
- CGFloat ci = (rssi - 49) / (10 * 4.);
- NSString *length = [NSString stringWithFormat:@"Found hotpoint:%@,distence:%.1fm",_peripheral,pow(10,ci)];
- [self updateLog:[NSString stringWithFormat:@"Distence:%@", length]];
- }
- //
- //
- //-(void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
- //{
- // DebugLog(@"%s,%@",__PRETTY_FUNCTION__,peripheral);
- // int rssi = abs([peripheral.RSSI intValue]);
- // CGFloat ci = (rssi - 49) / (10 * 4.);
- // NSString *length = [NSString stringWithFormat:@"Found hotpoint:%@,distence:%.1fm",_peripheral,pow(10,ci)];
- // [self updateLog:[NSString stringWithFormat:@"Distence:%@", length]];
- //}
- //已发现服务
- -(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
- [self updateLog:@"Found service."];
- int i=0;
- for (CBService *s in peripheral.services) {
- [self.nServices addObject:s];
- }
- for (CBService *s in peripheral.services) {
- [self updateLog:[NSString stringWithFormat:@"%d :service UUID: %@(%@)",i,s.UUID.data,s.UUID]];
- i++;
- [peripheral discoverCharacteristics:nil forService:s];
- // if ([s.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]])
- // {
- // BOOL replace = NO;
- // // Match if we have this device from before
- // for (int i=0; i < _nDevices.count; i++) {
- // CBPeripheral *p = [_nDevices objectAtIndex:i];
- // if ([p isEqual:peripheral]) {
- // [_nDevices replaceObjectAtIndex:i withObject:peripheral];
- // replace = YES;
- // }
- // }
- // if (!replace) {
- // [_nDevices addObject:peripheral];
- //// [_bluetoothTable reloadData];
- // }
- // }
- }
- }
- //已搜索到Characteristics
- -(void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
- [self updateLog:[NSString stringWithFormat:@"service:%@ (%@)",service.UUID.data ,service.UUID]];
- for (CBCharacteristic *c in service.characteristics)
- {
- [self updateLog:[NSString stringWithFormat:@"Characteristic UUID: %@ (%@)",c.UUID.data,c.UUID]];
-
- if(c.properties& CBCharacteristicPropertyWrite) //写
- // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]])
- {
- _writeCharacteristic = c;
- }
- if (c.properties&CBCharacteristicPropertyNotify) // 通知
- // if ([c.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]])
- {
- [_peripheral readValueForCharacteristic:c];
- [_peripheral setNotifyValue:YES forCharacteristic:c];
- }
- }
- }
- - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
- if(error)
- DebugLog(@"!Disconnect %ld %@",error.code,[error localizedDescription]);
- [self updateLog:[NSString stringWithFormat:@"Disconnect device:[%@]", peripheral.name]];
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onStatusChanged:)])){
- [_eventsFeedback onStatusChanged:@"Disconnected"];
- }
-
- if ([self.peripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
- [self updateLog:@"Retrying..."];
- DebugLog(@"Retrying");
- [self.manager connectPeripheral:peripheral options:nil];
- }
- }
- - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- {
- DebugLog(@"didUpdateValueForCharacteristic from Characteristic %@",characteristic.UUID);
- NSData * data = characteristic.value;
- if(data==nil)
- {
- DebugLog(@"Scan Data is empty");
- return;
- }
-
- NSString *datastring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
-
- // NSString *datastring1 = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
- // NSString *datastring2 = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
- // NSString *datastring3 = [[NSString alloc] initWithData:data encoding:NSUTF32StringEncoding];
-
- //
- // = 1, /* 0..127 only */
- // NSNEXTSTEPStringEncoding = 2,
- // NSJapaneseEUCStringEncoding = 3,
- //
- // NSISOLatin1StringEncoding = 5,
- // NSSymbolStringEncoding = 6,
- // NSNonLossyASCIIStringEncoding = 7,
- // NSShiftJISStringEncoding = 8, /* kCFStringEncodingDOSJapanese */
- // NSISOLatin2StringEncoding = 9,
- // NSUnicodeStringEncoding = 10,
- // NSWindowsCP1251StringEncoding = 11, /* Cyrillic; same as AdobeStandardCyrillic */
- // NSWindowsCP1252StringEncoding = 12, /* WinLatin1 */
- // NSWindowsCP1253StringEncoding = 13, /* Greek */
- // NSWindowsCP1254StringEncoding = 14, /* Turkish */
- // NSWindowsCP1250StringEncoding = 15, /* WinLatin2 */
- // NSISO2022JPStringEncoding = 21, /* ISO 2022 Japanese encoding for e-mail */
- // NSMacOSRomanStringEncoding = 30,
- //
- // /* An alias for NSUnicodeStringEncoding */
- //
- // NSUTF16BigEndianStringEncoding = 0x90000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
- // NSUTF16LittleEndianStringEncoding = 0x94000100, /* NSUTF16StringEncoding encoding with explicit endianness specified */
- //
- // NSUTF32StringEncoding = 0x8c000100,
- // NSUTF32BigEndianStringEncoding = 0x98000100, /* NSUTF32StringEncoding encoding with explicit endianness specified */
- // NSUTF32LittleEndianStringEncoding = 0x9c000100
- //
-
- datastring = [datastring stringByReplacingOccurrencesOfString:@"\r" withString:@""];
- if(datastring.length==0)
- {
- DebugLog(@"Scan Data is empty");
- return;
- }
- else
- DebugLog(@"Scan value %@",datastring);
-
-
- if((_eventsFeedback!=nil)&&([_eventsFeedback respondsToSelector:@selector(onDecodedData:)])){
- [_eventsFeedback onDecodedData:datastring];
- }
-
- [self addlog:datastring];
-
- // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF02"]]) {
- // NSData * data = characteristic.value;
- // Byte * resultByte = (Byte *)[data bytes];
- // for(int i=0;i<[data length];i++)
- // printf("testByteFF02[%d] = %d\n",i,resultByte[i]);
- // if (resultByte[1] == 0) {
- // }else if (resultByte[1] == 1) {
- // [self updateLog:@"未知错误"];
- // }else if (resultByte[1] == 2) {
- // [self updateLog:@"鉴权失败"];
- // }
- // }
- // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF04"]]) {
- // NSData * data = characteristic.value;
- // Byte * resultByte = (Byte *)[data bytes];
- // for(int i=0;i<[data length];i++)
- // printf("testByteFF04[%d] = %d\n",i,resultByte[i]);}
- // if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FF05"]]) {
- // NSData * data = characteristic.value;
- // Byte * resultByte = (Byte *)[data bytes];
- // for(int i=0;i<[data length];i++)
- // printf("testByteFF05[%d] = %d\n",i,resultByte[i]);
- // if (resultByte[0] == 0) {
- // // 设备加解锁状态 0 撤防 1 设防
- // [self updateLog:@"当前车辆撤防状态"];
- // }else if (resultByte[0] == 1) {
- // // 设备加解锁状态 0 撤防 1 设防
- // [self updateLog:@"当前车辆设防状态"];
- // }
- // }
- }
- //中心读取外设实时数据
- - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
- if (error) {
- DebugLog(@"Error changing notification state: %@", error.localizedDescription);
- [self updateLog:[NSString stringWithFormat:@"Error changing notification state: %@. Disconnect", error.localizedDescription]];
- // [self.manager cancelPeripheralConnection:self.peripheral];
-
-
- }
- // Notification has started
- if (characteristic.isNotifying) {
- [peripheral readValueForCharacteristic:characteristic];
- } else { // Notification has stopped
- // so disconnect from the peripheral
- DebugLog(@"Notification stopped on %@. Disconnecting", characteristic);
- [self updateLog:[NSString stringWithFormat:@"Notification stopped on %@. Disconnecting", characteristic]];
- // [self.manager cancelPeripheralConnection:self.peripheral];
- [self disconnectDevice];
- }
- }
- //用于检测中心向外设写数据是否成功
- -(void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- {
- if (error) {
- DebugLog(@"=======%@",error.userInfo);
-
-
- [self updateLog:[RAConvertor dict2string:error.userInfo]];
- }else{
- DebugLog(@"发送数据成功");
- [self updateLog:@"Send data."];
- }
- /* When a write occurs, need to set off a re-read of the local CBCharacteristic to update its value */
- [peripheral readValueForCharacteristic:characteristic];
- }
- #endif
- //
- ////#parammark tableview
- //
- //- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
- // return self.nDevices.count;
- //}
- //
- //- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
- // static NSString *CellIdentifier = @"Cell";
- // // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
- // UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- // if (!cell) {
- // cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
- // }
- //
- // CBPeripheral *p=self.nDevices[indexPath.item];
- // NSString* name = p.name;
- // if(name.length==0)
- // name=@"NO Name";
- // cell.textLabel.text = name;
- //
- // return cell;
- //}
- //-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
- //{
- // CBPeripheral *p=self.nDevices[indexPath.item];
- //
- // _peripheral = p;
- // [_manager connectPeripheral:_peripheral options:nil];
- //}
- #pragma mark new_download
- - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
- if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
- if(/*[challenge.protectionSpace.host isEqualToString:@"96.75.188.41"]*/ true){
- NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
- completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
- }
- }
- }
- -(void)handle_download1:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
- {
- //操作有两种,start stop;
- //结果有四种, wait , downloading, pause, finish
-
- dispatch_async(dispatch_get_main_queue(), ^{
- // debug;
- // NSString* file_name=[url lastPathComponent];
- //暂停<->开始转换
-
- // bool isdownloading = [self isdownloading:file_name];
- if (start)
- {//开始下载
-
-
-
-
-
-
- DebugLog(@"%d start",taskidx);
-
- self.current_task=taskidx;
-
-
-
- // NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
- //
- // // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
- // //
- // //
- // // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
- // //
- // // //设置请求头(GET)
- // // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
- // // [request setValue:range forHTTPHeaderField:@"Range"];
- // //
- // // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
- //
- //
- // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
- //
- // //设置请求头(GET)
- // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
- // [request setValue:range forHTTPHeaderField:@"Range"];
- //
-
-
- // RANetworkTaskDelegate *delegate = [RANetworkTaskDelegate sharedInstance];
-
-
- NSURLSession *session = nil;
-
- NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
- config.timeoutIntervalForRequest = JSON_TIMEOUT;
-
- NSOperationQueue *queue = [[NSOperationQueue alloc] init];
-
- session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:queue];
-
-
-
-
- NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
-
- req.HTTPMethod = @"GET";
- // long offset = [self getcurrentLength:taskidx];
- // if (offset > 0) {
- // [req addValue:[NSString stringWithFormat:@"bytes=%ld-",(unsigned long)offset] forHTTPHeaderField:@"Range"];
- // }
-
-
- NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
- [req setValue:range forHTTPHeaderField:@"Range"];
-
-
- NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:req];
-
- [downloadTask resume];
- self.session =session;
- self.curr_task = downloadTask;
-
- }else{ //暂停
- DebugLog(@"%d pause",taskidx);
-
-
- [self.curr_task cancel];
-
- self.curr_task = nil;
- // [self.connection cancel];
- // self.connection = nil;
- }
- });
- }
- - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
-
- NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
-
- if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
-
-
- DebugLog(@"%d begin",self.current_task);
-
- long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
-
-
- //获取下载文件大小
- // self.fileLength = response.expectedContentLength;
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
- //获取文件名
- //self.fileName = response.suggestedFilename;
-
- currenttask[@"fileName"] = response.suggestedFilename;
- currenttask[@"response"] = @"true";
- [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- //文件路径
- NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
-
- NSString * ver = self.download_task[@"ver"];
- NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
- NSString *filePath = [temp stringByAppendingPathComponent:location];
- DebugLog(@"save to: %@",filePath);
-
- if (position>0) {
- //不需要创建文件;
- //创建一个用来写数据的文件句柄
- self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
- return;
- }
- // 第一次获取的才是文件正确大小
- currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
- //创建一个空的文件到沙盒
- NSFileManager *fileManager = [NSFileManager defaultManager];
- [fileManager createFileAtPath:filePath contents:nil attributes:nil];
-
- //创建一个用来写数据的文件句柄
- self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
- }else{
-
- //debug 这里缺少文件的情况还没处理
-
- [self.connection cancel];
- self.connection = nil;
- DebugLog(@"该文件不存在");
- NSString* str_status=[NSString stringWithFormat:@"Server return %d.",(int)httpresponse.statusCode];
-
- [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
- [self add_downloadlog:str_status];
- }
- completionHandler(NSURLSessionResponseAllow);
- }
- - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
-
-
- //移动到文件末尾
- [self.fileHandle seekToEndOfFile];
-
- //写入数据到文件
- [self.fileHandle writeData:data];
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
- long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
- position += data.length;
- currenttask[@"position"] = [NSNumber numberWithLongLong:position];
-
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- //更新画面中的进度
- int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
-
-
-
-
-
- double progress = (double)position/fileLength;
-
- self.file_progress = progress;
- [self.settingUI onProgressUpdate];
- }
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
-
- // double progress = (double)totalBytesSent / totalBytesExpectedToSend;
- }
- - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
-
- // if (self.decryptHandler) {
- //
- // self.result.decryptHandler = self.decryptHandler;
- //
- // }
- //
- // if (error) {
- //
- // self.result.error = error;
- //
- // DebugLog(@"Delegate recv Error: %@",error.localizedDescription);
- //
- // }
- //
- // self.result.data = self.recvData;
- //
- // DebugLog(@"Delegate recv data %@",self.recvData);
- //
- //
- //
-
-
-
-
- if (error) {
- DebugLog(@"%d error message:%@",self.current_task,error);
-
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
-
-
-
-
-
-
- // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
- currenttask[@"status"] = @"pause";
- int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
-
- [self download_offline:true checkdiskspace:false];
-
- } else {
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
-
-
-
-
- [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
-
- DebugLog(@"%d finish",self.current_task);
- currenttask[@"position"] = [NSNumber numberWithLongLong:0];
-
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- int result=[self unpack];
- NSString* temp = NSTemporaryDirectory();
-
- NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
-
-
-
- NSString * ver = self.download_task[@"ver"];
-
- NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
-
- NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
-
- switch (result) {
- case UNZIP_FILE_DAMAGE:
- {
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
- currenttask[@"status"] = @"pause";
- int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
- break;
- }
- case UNZIP_SUCCESS:
- {
- NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
-
- if([type isEqualToString:@"img"])
- {
-
- NSString* parent_path = self.download_task[@"path"];
- if(parent_path.length==0)
- parent_path=@"";
- parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
- parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
- NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
-
-
-
- NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
-
- BOOL bdir=YES;
- NSError *error = nil;
- if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
- {
-
- bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
-
- if(!bsuccess)
- DebugLog(@"Create temp folder failed");
- }
-
- error=nil;
- // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
- // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
-
- // NSError *error = nil;
- // NSURL* uf=[NSURL fileURLWithPath:imagecache];
- // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
- // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
- // backupItemName:backup
- // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
- // resultingItemURL:nil error:&error])
- if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
- // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
- {
- DebugLog(@"move image folder failed");
- }
- else
- {
- currenttask[@"status"] = @"finish";
- DebugLog(@"move image folder successful");
- }
-
- }
- else if([type isEqualToString:@"sql"])
- {
- // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
- NSString * ver = self.download_task[@"ver"];
- NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
- tempdb=[temp stringByAppendingPathComponent:tempdb];
- sqlite3* tdb=[iSalesDB get_db_at:tempdb];
-
-
- [self add_downloadlog:@"updating local database..."];
-
-
- @try {
- char *errmsg=NULL;
- // [iSalesDB disable_trigger]
- [iSalesDB disable_trigger];
-
- if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
- {
-
- sqlite3_exec(tdb, "drop trigger if exists wishlist_insert;drop trigger if exists wishlist_update;drop trigger if exists wishlist_delete;drop trigger if exists offline_portfolio_insert;drop trigger if exists offline_portfolio_update;drop trigger if exists offline_portfolio_delete;drop trigger if exists offline_pdf_insert;drop trigger if exists offline_pdf_update;drop trigger if exists offline_pdf_delete;drop trigger if exists offline_pdf;", NULL, NULL, &errmsg);
-
- sqlite3_free(errmsg);
- DebugLog(@"开启事务");
- NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
-
- NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
- int count = [orderjson[@"count"] intValue];
- for(int i=0;i<count;i++)
- {
- NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
- NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
- NSError *error = nil;
- NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
- //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
-
-
-
-
- if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
- {
- //throw exception;
- if(errmsg==nil)
- errmsg="Unknown error.";
- NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
- [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
- }
-
- sqlite3_free(errmsg);
- }
-
-
- sqlite3_exec(tdb, "CREATE TRIGGER if not exists wishlist_insert after insert on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists wishlist_update after update on wishlist BEGIN select offline_dirty(); UPDATE wishlist SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists wishlist_delete after DELETE ON wishlist BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_pdf_insert after insert on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_pdf_update after update on offline_pdf BEGIN select offline_dirty(); UPDATE offline_pdf SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_pdf_delete after DELETE ON offline_pdf BEGIN select offline_dirty(); END;CREATE TRIGGER if not exists offline_portfolio_insert after insert on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime') WHERE _id=new._id;END;CREATE TRIGGER if not exists offline_portfolio_update after update on offline_portfolio BEGIN select offline_dirty(); UPDATE offline_portfolio SET modify_time= datetime('now', 'localtime'), is_dirty = 1 WHERE _id=new._id; END;CREATE TRIGGER if not exists offline_portfolio_delete after DELETE ON offline_portfolio BEGIN select offline_dirty(); END;", NULL, NULL, &errmsg);
- }
- //提交事务
- if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
-
- DebugLog(@"提交事务");
-
- sqlite3_free(errmsg);
- }
-
- [self add_downloadlog:@"updating local database successful"];
- currenttask[@"status"] = @"finish";
-
- }
-
-
- @catch (NSException *exception) {
- char *errmsg=NULL;
- [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
- [self add_downloadlog:@"updating local database failed rollback..."];
- if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
- DebugLog(@"回滚事务");
-
-
-
-
-
-
- }
- else
- {
- [self add_downloadlog:@"rollback failed."];
- }
-
-
- NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
- currenttask[@"status"] = @"pause";
- //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
- currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
- self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
-
- // self.currentLength = 0;
- // self.fileLength = 0;
- [self.fileHandle closeFile];
- self.fileHandle = nil;
- [self.connection cancel];
- self.connection = nil;
- //break;
- }
- @finally {
-
- // [iSalesDB enable_trigger]
- [iSalesDB enable_trigger];
- sqlite3_close(tdb);
- // [iSalesDB close_db:tdb];
- // [self SelectData];
- }
-
- }
- else if([type isEqualToString:@"script"])
- {
- currenttask[@"status"] = @"finish";
- }
- else if([type isEqualToString:@"resource"])
- {
- currenttask[@"status"] = @"finish";
- }
- // debug
- // int c=self.current_task+1;
- // double t=[ self.download_task[@"count"] doubleValue];
- double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
- self.overall_progress = oprogress;
- [self.settingUI onProgressUpdate];
- break;
- }
- case UNZIP_NO_SPACE:
- {
- [self add_downloadlog:@"Disk space not enough."];
-
- break;
- }
- case UNZIP_OPEN_FAILED:
- {
- [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
- break;
- }
- default:
- break;
- }
- dispatch_sync(dispatch_get_main_queue(), ^{
- [self download_offline:true checkdiskspace:false];
- });
-
- }
- printf("net work complete\n");
-
- //
- [session invalidateAndCancel];
- }
- @end
|