AppDelegate.m 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033
  1. //
  2. // AppDelegate.m
  3. // RedAnt ERP Suite
  4. //
  5. // Created by Ray on 14-5-19.
  6. // Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "UILabel+FontAppearance.h"
  10. #import "MainViewController.h"
  11. #import "RAPDFViewController.h"
  12. #import "ZipArchive.h"
  13. #import "DefaultAppearance.h"
  14. #import "OLDataProvider.h"
  15. #import "AFHTTPSessionManager.h"
  16. #import "SelectUploadOrderViewController.h"
  17. #import "iSalesDB.h"
  18. #import "iSalesNetwork.h"
  19. #import "NotificationNameCenter.h"
  20. #import "CustomerEditViewController.h"
  21. #import "CreateOrderViewController.h"
  22. #import "OrderDetailViewController.h"
  23. #import "AddressEditorViewController.h"
  24. #import "config.h"
  25. #import "Singleton.h"
  26. #import "Analytics.h"
  27. #import "GoogleAnalyst.h"
  28. #import "ERPUtils.h"
  29. #import "iSalesNetwork.h"
  30. #define UNZIP_OPEN_FAILED 0
  31. #define UNZIP_SUCCESS 1
  32. #define UNZIP_NO_SPACE 2
  33. #define UNZIP_FILE_DAMAGE 3
  34. @interface AppDelegate ()
  35. @property (nonatomic,strong) NSDate *forgroundDate;
  36. @end
  37. @implementation AppDelegate
  38. {
  39. #ifdef USE_SOFTSCAN
  40. DeviceInfo* _softScanDeviceInfo;
  41. #endif
  42. DeviceInfo* _deviceInfoToTrigger;
  43. }
  44. @synthesize price_hidden = _price_hidden;
  45. @synthesize ScanApi;
  46. @synthesize ScanApiConsumer;
  47. @synthesize scanApiVersion;
  48. //@synthesize devices;
  49. -(void) set_priceHidden:(bool)price_hidden
  50. {
  51. _price_hidden = price_hidden;
  52. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  53. // NSObject* obj;
  54. // [obj isEqual:@""];
  55. [avc showHidePrice];
  56. }
  57. -(void) setCustomerInfo:(NSMutableDictionary*)customerInfo
  58. {
  59. if (self.user_type == USER_ROLE_CUSTOMER && _customerInfo) {
  60. return;
  61. }
  62. _customerInfo=customerInfo;
  63. [(MainViewController*)self.main_vc reloadWish:YES immediately:NO];
  64. // DebugLog(@"%@",_customerInfo.class);
  65. // DebugLog(@"%@",customerInfo.class);
  66. int count=customerInfo[@"count"];
  67. //assert(count==0);
  68. }
  69. -(void) set_main_button_panel
  70. {
  71. dispatch_async(dispatch_get_main_queue(), ^{
  72. if(self.main_vc==nil)
  73. return;
  74. MainViewController * main_vc= (MainViewController*)self.main_vc;
  75. if(self.user_type==USER_ROLE_CUSTOMER)
  76. {
  77. main_vc.customer_bp.hidden=false;
  78. main_vc.employee_bp.hidden = true;
  79. }
  80. else
  81. {
  82. main_vc.customer_bp.hidden=true;
  83. main_vc.employee_bp.hidden = false;
  84. }
  85. });
  86. }
  87. -(void) update_count_mark
  88. {
  89. dispatch_async(dispatch_get_main_queue(), ^{
  90. if(self.main_vc==nil)
  91. return;
  92. MainViewController * main_vc= (MainViewController*)self.main_vc;
  93. //contact button
  94. if(self.user==nil)
  95. {
  96. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  97. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  98. main_vc.btnContact.hidden = YES;
  99. }
  100. else
  101. {
  102. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  103. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  104. if(self.customerInfo==nil)
  105. {
  106. // contact=@"No Name"; if(customerinfo==nil)
  107. // {
  108. contact=@"Select Contact";
  109. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  110. }
  111. else
  112. {
  113. if(contact==nil||contact.length==0)
  114. {
  115. contact=@"No Name";
  116. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  117. }
  118. else
  119. {
  120. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  121. }
  122. }
  123. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  124. if(contact.length>0)
  125. [arr_contact addObject:contact];
  126. if(customer.length>0)
  127. [arr_contact addObject:customer];
  128. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  129. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  130. }
  131. //cart
  132. if(self.user==nil||self.cart_count==0)
  133. {
  134. main_vc.label_ccount.hidden = true;
  135. main_vc.label_cccount.hidden=true;
  136. }
  137. else
  138. {
  139. NSString* strcount;
  140. if(self.cart_count>999)
  141. strcount=@"999+";
  142. else
  143. strcount=[NSString stringWithFormat:@"%ld",self.cart_count];
  144. main_vc.label_ccount.text = strcount;
  145. if(strcount.length==1)
  146. main_vc.label_ccount.frame = CGRectMake(128, 0, 21, 21);
  147. if(strcount.length==2)
  148. main_vc.label_ccount.frame = CGRectMake(122, 0, 25, 21);
  149. if(strcount.length==3)
  150. main_vc.label_ccount.frame = CGRectMake(118, 0, 31, 21);
  151. if(strcount.length==4)
  152. main_vc.label_ccount.frame = CGRectMake(103, 0, 42, 21);
  153. main_vc.label_ccount.hidden = false;
  154. main_vc.label_cccount.text = strcount;
  155. if(strcount.length==1)
  156. main_vc.label_cccount.frame = CGRectMake(128, 0, 21, 21);
  157. if(strcount.length==2)
  158. main_vc.label_cccount.frame = CGRectMake(122, 0, 25, 21);
  159. if(strcount.length==3)
  160. main_vc.label_cccount.frame = CGRectMake(118, 0, 31, 21);
  161. if(strcount.length==4)
  162. main_vc.label_cccount.frame = CGRectMake(103, 0, 42, 21);
  163. main_vc.label_cccount.hidden = false;
  164. }
  165. //wishlist
  166. if(self.user==nil||self.wish_count==0)
  167. {
  168. main_vc.label_wcount.hidden = true;
  169. main_vc.label_cwcount.hidden = true;
  170. }
  171. else
  172. {
  173. NSString* strcount;
  174. if(self.wish_count>999)
  175. strcount=@"999+";
  176. else
  177. strcount=[NSString stringWithFormat:@"%ld",self.wish_count];
  178. main_vc.label_wcount.text = strcount;
  179. if(strcount.length==1)
  180. main_vc.label_wcount.frame = CGRectMake(433, 0, 21, 21);
  181. if(strcount.length==2)
  182. main_vc.label_wcount.frame = CGRectMake(433-6, 0, 25, 21);//-6
  183. if(strcount.length==3)
  184. main_vc.label_wcount.frame = CGRectMake(433-10, 0, 31, 21);//-10
  185. if(strcount.length==4)
  186. main_vc.label_wcount.frame = CGRectMake(433-21, 0, 42, 21);//-21
  187. main_vc.label_wcount.hidden = false;
  188. main_vc.label_cwcount.text = strcount;
  189. if(strcount.length==1)
  190. main_vc.label_cwcount.frame = CGRectMake(433-79, 0, 21, 21);
  191. if(strcount.length==2)
  192. main_vc.label_cwcount.frame = CGRectMake(433-6-79, 0, 25, 21);//-6
  193. if(strcount.length==3)
  194. main_vc.label_cwcount.frame = CGRectMake(433-10-79, 0, 31, 21);//-10
  195. if(strcount.length==4)
  196. main_vc.label_cwcount.frame = CGRectMake(433-21-79, 0, 42, 21);//-21
  197. main_vc.label_cwcount.hidden = false;
  198. }
  199. });
  200. }
  201. -(void) closeOrder
  202. {
  203. self.order_code = nil;
  204. self.order_customer_id = nil;
  205. if(self.user_type!=USER_ROLE_CUSTOMER)
  206. {
  207. self.customerInfo = nil;
  208. self.contact_id = nil;
  209. }
  210. // [self SetMode:nil];
  211. // [self SetSo:nil];
  212. [((MainViewController*)self.main_vc) reloadCart:true immediately:false];
  213. [((MainViewController*)self.main_vc) reloadOrder:true immediately:false];
  214. }
  215. -(void) switchToPreviousVC
  216. {
  217. MainViewController * main_vc= (MainViewController*)self.main_vc;
  218. [main_vc switchToPreviousVC];
  219. }
  220. -(void) SetMode:(NSString*)mode1
  221. {
  222. __block NSString* blockmode= mode1;
  223. dispatch_async(dispatch_get_main_queue(), ^{
  224. if(self.offline_mode)
  225. blockmode =@"Regular Mode";
  226. if(self.main_vc==nil)
  227. return;
  228. MainViewController * main_vc= (MainViewController*)self.main_vc;
  229. if(self.user==nil)
  230. {
  231. NSString* title = [NSString stringWithFormat:@"Sign in"];
  232. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  233. [main_vc.btnContact setTitle:@"" forState:UIControlStateNormal];
  234. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  235. main_vc.btnContact.hidden = YES;
  236. main_vc.labelMode.text=nil;
  237. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  238. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  239. // main_vc.buttonUser.hidden=true;
  240. // main_vc.buttonUser.hidden=false;
  241. // [main_vc.headerView setNeedsDisplay];
  242. // [main_vc.headerView setNeedsLayout];
  243. return;
  244. }
  245. else
  246. {
  247. if(self.user_type==USER_ROLE_CUSTOMER)
  248. {
  249. NSString* title = [NSString stringWithFormat:@"%@",self.user];
  250. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  251. main_vc.labelMode.text=nil;
  252. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  253. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  254. // main_vc.buttonUser.hidden=true;
  255. // main_vc.buttonUser.hidden=false;
  256. // [main_vc.headerView setNeedsDisplay];
  257. // [main_vc.headerView setNeedsLayout];
  258. }
  259. else
  260. {
  261. if([blockmode isEqualToString:@"Regular Mode"])
  262. {
  263. self.mode=@"RM";
  264. NSString* title = self.user;
  265. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  266. main_vc.labelMode.text=self.mode;
  267. [main_vc.labelMode setTextColor:UIColorFromRGB(0x336699)];
  268. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x996633) forState:UIControlStateNormal];
  269. // main_vc.buttonUser.hidden=true;
  270. // main_vc.buttonUser.hidden=false;
  271. // [main_vc.headerView setNeedsDisplay];
  272. // [main_vc.headerView setNeedsLayout];
  273. }
  274. else
  275. {
  276. self.mode=@"TM";
  277. NSString* title = self.user;
  278. [main_vc.buttonUser setTitle:title forState:UIControlStateNormal];
  279. main_vc.labelMode.text=self.mode;
  280. [main_vc.labelMode setTextColor:UIColorFromRGB(0x009966)];
  281. // [main_vc.buttonUser setTitleColor:UIColorFromRGB(0x009966) forState:UIControlStateNormal];
  282. // main_vc.buttonUser.hidden=true;
  283. // main_vc.buttonUser.hidden=false;
  284. // [main_vc.headerView setNeedsDisplay];
  285. // [main_vc.headerView setNeedsLayout];
  286. }
  287. }
  288. NSString * contact =[self.customerInfo valueForKey:@"customer_contact"];
  289. NSString * customer=[self.customerInfo valueForKey:@"customer_name"];
  290. if(self.customerInfo==nil)
  291. {
  292. // contact=@"No Name"; if(customerinfo==nil)
  293. // {
  294. contact=@"Select Contact";
  295. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  296. }
  297. else
  298. {
  299. if(contact==nil||contact.length==0)
  300. {
  301. contact=@"No Name";
  302. [main_vc.btnContact setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
  303. }
  304. else
  305. {
  306. [main_vc.btnContact setTitleColor:UIColorFromRGB(0x009900) forState:UIControlStateNormal];
  307. }
  308. }
  309. NSMutableArray* arr_contact = [[NSMutableArray alloc] init];
  310. if(contact.length>0)
  311. [arr_contact addObject:contact];
  312. if(customer.length>0)
  313. [arr_contact addObject:customer];
  314. NSString *contact_string = [arr_contact componentsJoinedByString:@" @"];
  315. [main_vc.btnContact setTitle:contact_string forState:UIControlStateNormal];
  316. }
  317. });
  318. }
  319. -(void) SetSo:(NSString *)So
  320. {
  321. dispatch_async(dispatch_get_main_queue(), ^{
  322. if(self.main_vc==nil)
  323. return;
  324. MainViewController * main_vc= (MainViewController*)self.main_vc;
  325. if (self.user_type == USER_ROLE_CUSTOMER) {
  326. if (So == nil) {
  327. // 释放订单
  328. [Singleton sharedInstance].currentOrderIsMerged = NO;
  329. }
  330. }
  331. if(self.user==nil)
  332. {
  333. // NSString* title = [NSString stringWithFormat:@"Sign in"];
  334. main_vc.labelSo.text=nil;
  335. return;
  336. }
  337. else
  338. {
  339. // if(self.user_type==USER_ROLE_CUSTOMER)
  340. // {
  341. //
  342. //
  343. // main_vc.labelSo.text=nil;
  344. // // main_vc.buttonUser.hidden=true;
  345. // // main_vc.buttonUser.hidden=false;
  346. // // [main_vc.headerView setNeedsDisplay];
  347. // // [main_vc.headerView setNeedsLayout];
  348. // }
  349. // else
  350. {
  351. if(So.length==0)
  352. main_vc.labelSo.text=nil;
  353. else
  354. {
  355. NSString* text =[NSString stringWithFormat:@"SO#: %@",So];
  356. main_vc.labelSo.text=text;
  357. }
  358. }
  359. }
  360. });
  361. }
  362. //- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
  363. // if ([rootViewController isKindOfClass:[UITabBarController class]]) {
  364. // UITabBarController* tabBarController = (UITabBarController*)rootViewController;
  365. // return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
  366. // } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
  367. // UINavigationController* navigationController = (UINavigationController*)rootViewController;
  368. // return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
  369. // } else if (rootViewController.presentedViewController) {
  370. // UIViewController* presentedViewController = rootViewController.presentedViewController;
  371. // return [self topViewControllerWithRootViewController:presentedViewController];
  372. // } else {
  373. // return rootViewController;
  374. // }
  375. //}
  376. //- (UIViewController*)topViewController {
  377. // return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
  378. //}
  379. //-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
  380. ////   // Get topmost/visible view controller
  381. // UIViewController *currentViewController = [self topViewController];
  382. //
  383. // if ([currentViewController respondsToSelector:@selector(lockPortrait)]) {
  384. //
  385. // return UIInterfaceOrientationMaskPortrait;
  386. // }
  387. ////
  388. ////   // Only allow portrait (standard behaviour)
  389. // return UIInterfaceOrientationMaskAll;
  390. //}
  391. void UncaughtExceptionHandler(NSException *exception) {
  392. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  393. NSString* build =[infoDict objectForKey:@"CFBundleVersion"];
  394. NSString* version =[infoDict objectForKey:@"CFBundleShortVersionString"];
  395. NSString *versionNum = @"";
  396. /*
  397. #ifdef BUILD_NPD
  398. versionNum = [NSString stringWithFormat:@"Version: npd %@ Build %@",version,build];
  399. #endif
  400. #ifdef BUILD_HOMER
  401. versionNum = [NSString stringWithFormat:@"Version: HOMER %@ Build %@",version,build];
  402. #endif
  403. #ifdef BUILD_HMLG
  404. versionNum = [NSString stringWithFormat:@"Version: HOMELEGANCE %@ Build %@",version,build];
  405. #endif
  406. */
  407. versionNum = [NSString stringWithFormat:@"Version: %@ %@ Build %@",COMPANY_SHORT_NAME,version,build];
  408. versionNum = [versionNum stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  409. /**
  410. * 获取异常崩溃信息
  411. */
  412. NSArray *callStack = [exception callStackSymbols];
  413. NSString *reason = [exception reason];
  414. NSString *name = [exception name];
  415. NSString *content = [NSString stringWithFormat:@"异常错误报告\n exception_name: %@\n exception_reason: \n%@ \n exception_callStackSymbols: \n%@ \n",name,reason,[callStack componentsJoinedByString:@"\n"]];
  416. content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
  417. NSString *sql = [NSString stringWithFormat:@"insert into errlog (errmsg,params) values ('%@','%@');",versionNum,content];
  418. if ([Singleton sharedInstance].currentDB) {
  419. [iSalesDB close_db:[Singleton sharedInstance].currentDB];
  420. }
  421. [iSalesDB execSql:sql];
  422. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  423. [appDelegate writeUrgencyCache];
  424. }
  425. - (void)handleErrorLog {
  426. __block NSMutableArray *err_array = [NSMutableArray array];
  427. [iSalesDB jk_query:@"select errmsg,params,create_time from errlog;" completion:^(sqlite3_stmt *stmt, NSMutableDictionary *container, long *count) {
  428. const char *version_char = (char *)sqlite3_column_text(stmt, 0);
  429. const char *errlog_char = (char *)sqlite3_column_text(stmt, 1);
  430. const char *dateTime_char = (char *)sqlite3_column_text(stmt, 2);
  431. if (version_char == NULL)
  432. version_char = "";
  433. if (errlog_char == NULL)
  434. errlog_char = "";
  435. if (dateTime_char == NULL)
  436. dateTime_char = "";
  437. NSString *version_str = [NSString stringWithUTF8String:version_char];
  438. NSString *errlog_str = [NSString stringWithUTF8String:errlog_char];
  439. NSString *dateTime_str = [NSString stringWithUTF8String:dateTime_char];
  440. NSDictionary *err_dic = @{
  441. @"version" : version_str,
  442. @"errlog" : errlog_str,
  443. @"time" : dateTime_str
  444. };
  445. [err_array addObject:err_dic];
  446. }];
  447. if (err_array.count) {
  448. // 首先上传
  449. for (NSDictionary *err_dic in err_array) {
  450. NSString *version = [err_dic objectForKey:@"version"];
  451. NSString *errlog = [err_dic objectForKey:@"errlog"];
  452. NSString *time = [err_dic objectForKey:@"time"];
  453. NSString *result = [NSString stringWithFormat:@"version: %@ \n crash_datetime: %@ \n",version,time];
  454. NSDictionary *ret = [iSalesNetwork err_log:errlog result:result module:@"crash" code:0];
  455. // 上传成功之后清除纪录
  456. if ([[ret objectForKey:@"result"] integerValue] == 2) {
  457. [iSalesDB execSql:[NSString stringWithFormat:@"delete from errlog where create_time = '%@';",time]];
  458. }
  459. }
  460. }
  461. }
  462. - (void)dealWithUrgencyFile {
  463. NSDictionary *tmp_urgencyDic = [self readUrgencyCache];
  464. if (tmp_urgencyDic.allKeys.count > 2) {
  465. [self.urgencyDic removeAllObjects];
  466. [self.urgencyDic setObject:[NSNumber numberWithInt:0] forKey:@"count"];
  467. MainViewController *mainVC = [self.window.rootViewController.childViewControllers lastObject];
  468. UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
  469. NSString *user = [tmp_urgencyDic objectForKey:@"user"];
  470. if (![user isEqualToString:self.user]) {
  471. return;
  472. }
  473. BOOL offline_mode = [[tmp_urgencyDic objectForKey:@"offline_mode"] boolValue];
  474. if (!((self.offline_mode && offline_mode) || (!self.offline_mode && !offline_mode))) {
  475. return;
  476. }
  477. id count = [tmp_urgencyDic objectForKey:@"count"];
  478. int level_count = count ? [count integerValue] : 0;
  479. if (!level_count) {
  480. return;
  481. }
  482. for (int i = 0; i < level_count; i++) {
  483. NSString *level_key = [NSString stringWithFormat:@"level_%d",i];
  484. NSDictionary *urgencyDic = [tmp_urgencyDic objectForKey:level_key];
  485. NSString *className = [urgencyDic objectForKey:@"class_name"];
  486. NSString *restored_data_key = [NSString stringWithFormat:@"%@_restored_data",className];
  487. NSMutableDictionary *restored_data = [urgencyDic objectForKey:restored_data_key];
  488. dispatch_async(dispatch_get_main_queue(), ^{
  489. if ([className isEqualToString:@"CustomerEditViewController"]) {
  490. // CustomerEditViewController
  491. NSString *contact_id = [urgencyDic objectForKey:@"contact_id"];
  492. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  493. [params setValue:contact_id forKey:@"contact_id"];
  494. CustomerEditViewController * cuseditVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CustomerEditViewController"];
  495. cuseditVC.bnewcustomer=false;
  496. cuseditVC.url_type = URL_REMOTE;
  497. cuseditVC.request_url=URL_NEW_CUSTOMER;
  498. cuseditVC.params = params;
  499. cuseditVC.content_data_download = restored_data;
  500. // cuseditVC.delegate=self;
  501. [[mainVC navigationController] setNavigationBarHidden:NO animated:NO];
  502. [mainVC.navigationController pushViewController:cuseditVC animated:false];
  503. } else if ([className isEqualToString:@"CreateOrderViewController"]) {
  504. // CreateOrderViewController
  505. NSString *order_code = [urgencyDic objectForKey:@"order_code"];
  506. int order_status = [[urgencyDic objectForKey:@"order_status"] intValue];
  507. NSString *order_customer_id = [urgencyDic objectForKey:@"order_customer_id"];
  508. NSInteger userType = [[[NSUserDefaults standardUserDefaults] objectForKey:@"urgency_userType"] integerValue];
  509. NSString *so = [urgencyDic objectForKey:@"order_so"];
  510. self.order_customer_id = order_customer_id;
  511. // 首先通过order code 打开订单
  512. NSDictionary* order_json = [iSalesNetwork open_Order:order_code];
  513. dispatch_async(dispatch_get_main_queue(), ^{
  514. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  515. if([[order_json valueForKey:@"result"] intValue]==2)
  516. {
  517. self.order_code = order_code;
  518. self.order_status = order_status;
  519. [self SetSo:so];
  520. if (userType != USER_ROLE_CUSTOMER) {
  521. self.customerInfo = [[[iSalesNetwork request_CustomerInfo:order_customer_id] objectForKey:@"customerInfo"] mutableCopy];
  522. self.contact_id=[self.customerInfo valueForKey:@"customer_cid"];
  523. }
  524. [mainVC reloadOrder:true immediately:false];
  525. [mainVC reloadCart:true immediately:false];
  526. }
  527. else
  528. {
  529. [RAUtils message_alert:[order_json valueForKey:@"err_msg"] title:@"Open Order" controller:mainVC] ;
  530. }
  531. });
  532. // 再place order
  533. NSMutableDictionary *params = [NSMutableDictionary dictionary];
  534. CreateOrderViewController * orderinfoVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"CreateOrderViewController"];
  535. orderinfoVC.disable_dropdown_refresh=true;
  536. orderinfoVC.url_type = URL_REMOTE;
  537. orderinfoVC.request_url=URL_CARTDELIVERY;
  538. orderinfoVC.params = params;
  539. orderinfoVC.content_data_download = restored_data;
  540. orderinfoVC.resumeOrder = YES;
  541. [mainVC.navigationController pushViewController:orderinfoVC animated:true];
  542. } else if ([className isEqualToString:@"AddressEditorViewController"]) {
  543. // AddressEditorViewController
  544. AddressEditorViewController * addressVC =[mainStoryBoard instantiateViewControllerWithIdentifier:@"AddressEditorViewController"];
  545. addressVC.url_type = URL_REMOTE;
  546. addressVC.request_url=URL_ADDRESS_EDOTOR;
  547. NSMutableDictionary * params= [[NSMutableDictionary alloc] init];
  548. params[@"is_subaction"]=@"true";
  549. addressVC.params = params;
  550. addressVC.content_data_download = restored_data;
  551. [mainVC.navigationController pushViewController:addressVC animated:true];
  552. }// class_name
  553. });
  554. }
  555. }
  556. }
  557. - (void)handleUrgencyFile {
  558. __weak typeof(self) weakself = self;
  559. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  560. if (weakself) {
  561. __strong typeof(weakself) strongself = weakself;
  562. [strongself dealWithUrgencyFile];
  563. }
  564. });
  565. }
  566. - (void)writeUrgencyCache {
  567. if (!self.user) {
  568. return;
  569. }
  570. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  571. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  572. // [NSKeyedArchiver archiveRootObject:self.urgencyDic toFile:urgencyFile];
  573. [self.urgencyDic writeToFile:urgencyFile atomically:NO];
  574. // Place Order恢复是否能提交订单
  575. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_resume"];
  576. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInteger:self.user_type] forKey:@"urgency_userType"];
  577. if ([Singleton sharedInstance].currentOrderIsMerged && [Singleton sharedInstance].permissions_submit_order) {
  578. [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"urgency_submitOrder"];
  579. }
  580. }
  581. - (NSMutableDictionary *)readUrgencyCache {
  582. // 检查本地urgency文件,存在则加载进_urgencyDic
  583. NSFileManager *manager = [NSFileManager defaultManager];
  584. NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  585. NSString *urgencyFile = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_urgency",self.user]];
  586. NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
  587. if ([manager fileExistsAtPath:urgencyFile]) {
  588. resultDic = [NSMutableDictionary dictionaryWithContentsOfFile:urgencyFile];
  589. [manager removeItemAtPath:urgencyFile error:nil];
  590. }
  591. _urgencyDic = [NSMutableDictionary dictionary];
  592. return resultDic;
  593. }
  594. - (void)initialExceptionHandler {
  595. if (exception_switch == 1) {
  596. NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
  597. }
  598. }
  599. - (void)becomeObserver {
  600. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUrgencyFile) name:LoginOK_HandleUrgencyFile_Notification object:nil];
  601. }
  602. - (void)dealloc {
  603. [[NSNotificationCenter defaultCenter] removeObserver:self];
  604. }
  605. - (void)setUpGoogleAnalytics {
  606. // 初始化Google Analytics
  607. NSError *configureError;
  608. [[GGLContext sharedInstance] configureWithError:&configureError];
  609. if (configureError) {
  610. DebugLog(@"congigure googleAnalytics error: %@",configureError);
  611. }
  612. GAI *gai = [GAI sharedInstance];
  613. gai.trackUncaughtExceptions = YES;
  614. id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
  615. // Enable IDFA collection.
  616. tracker.allowIDFACollection = YES;
  617. // gai.dispatchInterval = 120;// 每隔 2 分钟调度一次数据
  618. // 调试使用
  619. // gai.logger.logLevel = kGAILogLevelVerbose;
  620. // [[GAI sharedInstance] setDryRun:YES];
  621. //
  622. }
  623. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  624. {
  625. self.window.backgroundColor = [UIColor whiteColor];
  626. // [RAUtils expression_varable:nil regex:nil];
  627. self.disable_trigger = false;
  628. [self initialExceptionHandler];
  629. [self becomeObserver];
  630. #ifdef BUILD_NPD
  631. [self setUpGoogleAnalytics];
  632. #endif
  633. [DefaultAppearance init_appearance];
  634. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  635. NSString *cachefolder = [paths objectAtIndex:0];
  636. NSString *upfolder = [cachefolder stringByAppendingPathComponent:@"upload_data"];
  637. // upfolder = [upfolder stringByAppendingPathComponent:serial];
  638. NSFileManager* fileManager = [NSFileManager defaultManager];
  639. BOOL bdir=YES;
  640. if(! [fileManager fileExistsAtPath:upfolder isDirectory:&bdir])
  641. {
  642. NSError *error = nil;
  643. bool bsuccess=[fileManager createDirectoryAtPath:upfolder withIntermediateDirectories:YES attributes:nil error:&error];
  644. if(!bsuccess)
  645. DebugLog(@"Create UPLOAD folder failed");
  646. }
  647. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  648. if(![fileManager fileExistsAtPath:pdfFolder isDirectory:&bdir])
  649. {
  650. NSError *error = nil;
  651. bool bsuccess=[fileManager createDirectoryAtPath:pdfFolder withIntermediateDirectories:YES attributes:nil error:&error];
  652. if(!bsuccess)
  653. DebugLog(@"Create PDF Cache folder failed");
  654. }
  655. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  656. //
  657. // DebugLog(@"文件已经存在了");
  658. //
  659. // }
  660. // NSString* order_filter_source_path =[[NSBundle mainBundle] pathForResource:@"status_filter_cadedate" ofType:@"json" ];
  661. // /var/folders/65/j0_0c8rx66zb29cjnjndr11r0000gn/T/AppIconMaker/appicon.png
  662. //
  663. //
  664. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  665. // NSString *documents = [paths objectAtIndex:0];
  666. // NSString *dist_path = [documents stringByAppendingPathComponent:@"status_filter_cadedate.json"];
  667. //
  668. //
  669. // if ([[NSFileManager defaultManager] fileExistsAtPath:dist_path]) {
  670. //
  671. // DebugLog(@"文件已经存在了");
  672. //
  673. // }
  674. // else
  675. // {
  676. //
  677. //
  678. //
  679. // // DebugLog(@"resourceSampleImagesFolderPath=%@",resourceFolderPath);
  680. //
  681. // NSData *mainBundleFile = [NSData dataWithContentsOfFile:order_filter_source_path];
  682. //
  683. // // DebugLog(@"mainBundleFile==%@",mainBundleFile);
  684. //
  685. // [[NSFileManager defaultManager] createFileAtPath:dist_path
  686. //
  687. // contents:mainBundleFile
  688. //
  689. // attributes:nil];
  690. //
  691. // }
  692. self.recent_model = [[NSMutableDictionary alloc]init];
  693. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  694. bool offline = [defaults boolForKey:@"EnableOfflineMode"] ;
  695. self.offline_mode = offline;
  696. // Override point for customization after application launch.
  697. if ( [iSalesDB initializeDb]!=0)
  698. DebugLog(@"init db failed");
  699. // disable apn
  700. // [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
  701. self.contact_id=nil;
  702. // NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  703. NSString * enable_cache = [defaults stringForKey:@"enable_cache"];
  704. if([enable_cache isEqualToString:@"false"])
  705. self.bEnable_Cache = false;
  706. else
  707. self.bEnable_Cache = true;
  708. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  709. self.build =[infoDict objectForKey:@"CFBundleVersion"];
  710. //scanner
  711. self.devices=[[NSMutableArray alloc]init];
  712. // change this to YES if you want SingleEntry to
  713. // confirm the decoded data
  714. _doAppDataConfirmation=NO;
  715. if(ScanApi==nil){
  716. #ifdef USE_SOFTSCAN
  717. // this is useful for SoftScan to keep a handle
  718. // that is used in the trigger button
  719. _softScanDeviceInfo=nil;
  720. #endif
  721. ScanApi=[[ScanApiHelper alloc]init];
  722. [ScanApi setDelegate:self];
  723. self.enable_ScannerLog = true;
  724. self.api_Status= API_STOP;
  725. // UIApplication * app = [UIApplication sharedApplication];
  726. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  727. //
  728. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  729. bool autolaunch = [defaults boolForKey:@"EnableScannerOnLaunch"] ;
  730. if(autolaunch==true)
  731. [self enableScanner:autolaunch];
  732. }
  733. // [self test_descrypt];
  734. // [self test_descrypt1];
  735. //UILabel * appearanceLabel = [UILabel appearanceWhenContainedIn:uialertcontroller.class, nil];
  736. // [appearanceLabel setAppearanceFont:[UIFont boldSystemFontOfSize:10]]; //for example
  737. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  738. [self handleErrorLog];
  739. });
  740. return YES;
  741. }
  742. //-(void)test_descrypt
  743. //{
  744. // sqlite3 *db = [iSalesDB get_db];
  745. //
  746. // int result= [iSalesDB AddExFunction:db];
  747. //
  748. // NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  749. // sqlite3_stmt * statement;
  750. //
  751. //
  752. // if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  753. // {
  754. //
  755. //
  756. // while (sqlite3_step(statement) == SQLITE_ROW)
  757. // {
  758. //
  759. //
  760. // char *url = (char*)sqlite3_column_text(statement, 0);
  761. // if(url==nil)
  762. // url="";
  763. // NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  764. // DebugLog(nsurl);
  765. //
  766. //
  767. //
  768. //
  769. // }
  770. // // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  771. //
  772. //
  773. // sqlite3_finalize(statement);
  774. // }
  775. //
  776. // [iSalesDB close_db:db];
  777. //}
  778. //
  779. //-(void)test_descrypt1
  780. //{
  781. // sqlite3 *db = [iSalesDB get_db];
  782. //
  783. // int result= [iSalesDB AddExFunction:db];
  784. //
  785. // NSString* sqlindex= @"CREATE INDEX hijk ON offline_contact (lower(company_name));";
  786. //
  787. // [iSalesDB execSql:sqlindex];
  788. ////
  789. //// NSString *sqlQuery = [NSString stringWithFormat:@"select decrypt(company_name) from offline_contact;"];
  790. //// sqlite3_stmt * statement;
  791. ////
  792. ////
  793. ////
  794. //// if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK)
  795. //// {
  796. ////
  797. ////
  798. //// while (sqlite3_step(statement) == SQLITE_ROW)
  799. //// {
  800. ////
  801. ////
  802. //// char *url = (char*)sqlite3_column_text(statement, 0);
  803. //// if(url==nil)
  804. //// url="";
  805. //// NSString *nsurl = [[NSString alloc]initWithUTF8String:url];
  806. //// DebugLog(nsurl);
  807. ////
  808. ////
  809. ////
  810. ////
  811. //// }
  812. //// // [ret setValue:[NSString stringWithFormat:@"%d",i] forKey:@"img_count"];
  813. ////
  814. ////
  815. //// sqlite3_finalize(statement);
  816. //// }
  817. //
  818. // [iSalesDB close_db:db];
  819. //}
  820. - (void)applicationWillResignActive:(UIApplication *)application
  821. {
  822. // 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.
  823. // 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.
  824. }
  825. - (void)applicationDidEnterBackground:(UIApplication *)application
  826. {
  827. [self download_offline:false checkdiskspace:false];
  828. // 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.
  829. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  830. NSTimeInterval timing = [[NSDate date] timeIntervalSinceDate:self.forgroundDate];
  831. self.forgroundDate = nil;
  832. #ifdef BUILD_NPD
  833. [GoogleAnalyst trackTimingWithCategory:@"foreground" interval:timing name:@"user used time" label:nil];
  834. #endif
  835. }
  836. - (void)applicationWillEnterForeground:(UIApplication *)application
  837. {
  838. // 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.
  839. }
  840. - (void)applicationDidBecomeActive:(UIApplication *)application
  841. {
  842. if(self.download_task!=nil)
  843. [self download_offline:true checkdiskspace:false];
  844. // 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.
  845. self.forgroundDate = [NSDate date];
  846. }
  847. -(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
  848. {
  849. DebugLog(@"======================================");
  850. DebugLog(@"===== MEMORY WORRING ! ==========");
  851. DebugLog(@"======================================");
  852. }
  853. - (void)applicationWillTerminate:(UIApplication *)application
  854. {
  855. // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
  856. }
  857. -(void) Logout
  858. {
  859. MainViewController * main_vc= (MainViewController*)self.main_vc;
  860. [main_vc logoutOrder];
  861. [main_vc hideMenu];
  862. [main_vc switchToHome];
  863. self.user = nil;
  864. self.password=nil;
  865. self.user_icon=nil;
  866. self.user_type = USER_ROLE_UNKNOWN;
  867. self.bLogin = false;
  868. self.contact_id=nil;
  869. self.customerInfo = nil;
  870. self.order_code = nil;
  871. [self.recent_model removeAllObjects];
  872. [self SetMode:nil];
  873. }
  874. //disable apn
  875. //-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  876. //{
  877. // self.duid = [[[[NSString stringWithFormat:@"%@",deviceToken] substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)] stringByReplacingOccurrencesOfString:@" " withString:@""];
  878. // DebugLog(@"regisger success:%@",deviceToken);
  879. //
  880. // //注册成功,将deviceToken保存到应用服务器数据库中
  881. //}
  882. #pragma mark - background download
  883. -(bool)isdownloading:(NSString*) file
  884. {
  885. return true;
  886. }
  887. -(long long)getcurrentLength:(int) taskidx
  888. {
  889. int position=[self.download_task [[NSString stringWithFormat:@"item_%d",taskidx]][@"position"] intValue];
  890. return position;
  891. }
  892. -(void)handle_download:(NSString *)url start:(bool) start type:(NSString*) type taskid:(int)taskidx
  893. {
  894. //操作有两种,start stop;
  895. //结果有四种, wait , downloading, pause, finish
  896. dispatch_async(dispatch_get_main_queue(), ^{
  897. NSString* file_name=[url lastPathComponent];
  898. //暂停<->开始转换
  899. // bool isdownloading = [self isdownloading:file_name];
  900. if (start)
  901. {//开始下载
  902. DebugLog(@"%d start",taskidx);
  903. self.current_task=taskidx;
  904. NSURL* _url = [NSURL URLWithString:url];//@"http://localhost/test.zip"];
  905. // _url = [NSURL URLWithString:@"https://rate.apexshipping.com/temp/apache-tomcat-8.0.22.zip"];
  906. //
  907. //
  908. // NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  909. //
  910. // //设置请求头(GET)
  911. // NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  912. // [request setValue:range forHTTPHeaderField:@"Range"];
  913. //
  914. // self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  915. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
  916. //设置请求头(GET)
  917. NSString *range = [NSString stringWithFormat:@"bytes=%lld-", [self getcurrentLength:taskidx]];
  918. [request setValue:range forHTTPHeaderField:@"Range"];
  919. self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
  920. }else{ //暂停
  921. DebugLog(@"%d pause",taskidx);
  922. [self.connection cancel];
  923. self.connection = nil;
  924. }
  925. });
  926. }
  927. -(void) upload_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress orderid:(NSArray*)arr_order
  928. {
  929. [self add_downloadlog:@"Begin sync, please wait."];
  930. [self add_downloadlog:@"Prepare upload data."];
  931. // NSArray* arr_order=[OLDataProvider enumOfflineOrder];
  932. NSDictionary* upjson=[OLDataProvider prepareUpload:arr_order];
  933. NSString* upfile=upjson[@"file"];
  934. {
  935. NSData* data = [NSData dataWithContentsOfFile: upfile];
  936. UIApplication * app = [UIApplication sharedApplication];
  937. AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  938. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  939. AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  940. serializer.timeoutInterval=300;
  941. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  942. if(appDelegate.user!=nil)
  943. [params setValue:appDelegate.user forKey:@"user"];
  944. // if(appDelegate.contact_id!=nil)
  945. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  946. if(appDelegate.password!=nil)
  947. [params setValue:appDelegate.password forKey:@"password"];
  948. #if TARGET_IPHONE_SIMULATOR//模拟器
  949. [params setValue:@"simulator_uuid" forKey:@"idfv"];
  950. #elif TARGET_OS_IPHONE//真机
  951. UIDevice * dev = [UIDevice currentDevice];
  952. NSUUID* uuid =dev.identifierForVendor;
  953. [params setValue:uuid.UUIDString forKey:@"idfv"];
  954. #endif
  955. NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_OFFLINE parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  956. [formData appendPartWithFileData:data name:@"upfile" fileName:[upfile lastPathComponent] mimeType:@"application/zip"];
  957. } error:nil];
  958. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  959. NSProgress *progress = nil;
  960. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  961. if (error) {
  962. NSString* err_msg = [error localizedDescription];
  963. DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  964. NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  965. DebugLog(@"data string: %@",str);
  966. [self add_downloadlog:err_msg];
  967. [self add_downloadlog:@"Can not connect to server please try again."];
  968. [self.settingUI onSyncFinish];
  969. } else {
  970. DebugLog(@"response ");
  971. NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  972. // 再将NSData转为字符串
  973. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  974. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  975. DebugLog(@"data string: %@",jsonStr);
  976. NSDictionary* json = responseObject;
  977. if([[json valueForKey:@"result"] intValue]==2)
  978. {
  979. NSString *out_of_stock_ids = [json valueForKey:@"stock_out_so_id"];
  980. if (out_of_stock_ids) {
  981. [RAUtils message_alert:[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] title:@"Warning" controller:self.main_vc];
  982. }
  983. [self add_downloadlog:@"Upload successful."];
  984. appDelegate.disable_trigger=true;
  985. NSString* so_id=[RAUtils arr2string:arr_order separator:@"," trim:true brackets:@"'"];
  986. [iSalesDB execSql:@"delete from offline_contact where not sync_data is null"];
  987. [iSalesDB execSql:@"delete from wishlist"];
  988. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_order where so_id in(%@)",so_id]];
  989. [iSalesDB execSql:[NSString stringWithFormat:@"delete from offline_cart where so_no in(%@)",so_id]];
  990. [iSalesDB execSql:@"delete from offline_portfolio"];
  991. [iSalesDB execSql:@"delete from offline_pdf"];
  992. [OLDataProvider offline_clear_PDFCache];
  993. NSString* contactMap = json[@"contactMap"];
  994. if(contactMap.length>0)
  995. {
  996. NSDictionary* contactjson = [RAUtils string2dict:contactMap];
  997. NSArray *keys= [contactjson allKeys];
  998. //遍历keys
  999. for(int i=0;i<[keys count];i++)
  1000. {
  1001. //得到当前key
  1002. NSString *key=[keys objectAtIndex:i];
  1003. //如果key不是pic,说明value是字符类型,比如name:Boris
  1004. NSString* value = [contactjson valueForKey:key];
  1005. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where customer_cid='%@' and order_id is null",value,key]];
  1006. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where receive_cid='%@' and order_id is null",value,key]];
  1007. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where sender_cid='%@' and order_id is null",value,key]];
  1008. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where shipping_billto_cid='%@' and order_id is null",value,key]];
  1009. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where billing_cid='%@' and order_id is null",value,key]];
  1010. [iSalesDB execSql:[NSString stringWithFormat:@"update offline_order set customer_cid='%@' where returnto_cid='%@' and order_id is null",value,key]];
  1011. }
  1012. }
  1013. // NSDictionary* contactjson= upjson[@"contact"];
  1014. // NSDictionary* wishlistjson= upjson[@"wishlist"];
  1015. // NSDictionary* orderjson= upjson[@"order"];
  1016. appDelegate.disable_trigger=false;
  1017. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1018. [defaults removeObjectForKey:@"Forcedownload"];
  1019. [defaults setBool:true forKey:@"Forcedownload"];
  1020. [defaults synchronize];
  1021. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1022. }
  1023. else
  1024. {
  1025. [self add_downloadlog:[json valueForKey:@"msg"]];
  1026. [self add_downloadlog:@"Sync canceled."];
  1027. [self.settingUI onSyncFinish];
  1028. }
  1029. }
  1030. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  1031. }];
  1032. [uploadTask resume];
  1033. }
  1034. return;
  1035. }
  1036. -(void) download_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress
  1037. {
  1038. NSString *plistPath = [RAUtils get_config_path];
  1039. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1040. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1041. {
  1042. ver= nil;
  1043. [self add_downloadlog:@"App required a fully sync."];
  1044. }
  1045. if(self.downloading)
  1046. return;
  1047. self.downloading=true;
  1048. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1049. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1050. NSString* pvid = [defaults stringForKey:@"vid"] ;
  1051. [self add_downloadlog:@"Checking offline data, this will take a few minute, please wait."];
  1052. NSMutableDictionary* json=[[iSalesNetwork check_Offline:ver useInternalAddress:buseinternaladdress vid:pvid] mutableCopy];
  1053. if([json[@"result"] intValue]!=2)
  1054. {
  1055. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1056. [self.settingUI onSyncFinish];
  1057. dispatch_async(dispatch_get_main_queue(), ^{
  1058. // self.downloadlog=nil;
  1059. self.downloading=false;
  1060. });
  1061. return;
  1062. }
  1063. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1064. NSMutableDictionary* download_json=nil;
  1065. // NSString* vid=@"31f4d59d-c229-47e3-9270-e15425777186";
  1066. NSString* downSerial=[json valueForKey:@"downSerial"];
  1067. [defaults removeObjectForKey:@"downSerial"];
  1068. [defaults setValue:downSerial forKey:@"downSerial"];
  1069. [defaults synchronize];
  1070. // sleep(3);
  1071. //UIAlertView * waitalert1 = [RAUtils waiting_alert:@"Please wait..." title:@"Server is preparing data for you"];
  1072. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1073. int count=0;
  1074. // __block bool preparing = true;
  1075. while ([[download_json valueForKey:@"result"] intValue]!=2&&count<REQUEST_DOWNLOAD_RETRY_TIMES) //超过60分钟还没准被好数据就视为服务器出错。
  1076. {
  1077. sleep(RETRY_DELAY);
  1078. count++;
  1079. download_json=[[iSalesNetwork download_Offline:downSerial] mutableCopy];
  1080. }
  1081. //服务器准备数据完毕,进入处理数据逻辑。
  1082. if(count>=REQUEST_DOWNLOAD_RETRY_TIMES)
  1083. {
  1084. [self add_downloadlog:@"Can not get offline data version, please try again later."];
  1085. dispatch_async(dispatch_get_main_queue(), ^{
  1086. // self.downloadlog=nil;
  1087. self.downloading=false;
  1088. });
  1089. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1090. [self.settingUI onSyncFinish];
  1091. return;
  1092. //一直没取到json,出错处理
  1093. }
  1094. else
  1095. {
  1096. if([download_json[@"count"] intValue]==0)
  1097. {
  1098. //没有找到更新包,当前是最新版本
  1099. [self add_downloadlog:@"You are up-to-date!"];
  1100. dispatch_async(dispatch_get_main_queue(), ^{
  1101. // self.downloadlog=nil;
  1102. self.downloading=false;
  1103. });
  1104. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1105. [self.settingUI onSyncFinish];
  1106. return;
  1107. }
  1108. else
  1109. {
  1110. [self add_downloadlog:@"Find a new version, downloading..."];
  1111. self.download_task = [download_json mutableCopy];
  1112. // self.download_task[@"abcdef"]=@"abcdef";
  1113. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1114. [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1115. [self download_offline:true checkdiskspace:true];
  1116. return;
  1117. }
  1118. }
  1119. });
  1120. }
  1121. -(void) check_offline:(NSString*) ver useInternalAddress:(bool)buseinternaladdress parentvc:(UIViewController*) parent
  1122. {
  1123. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1124. bool forcedownload = [defaults boolForKey:@"Forcedownload"];
  1125. if(forcedownload|| ver==nil)
  1126. {
  1127. [self download_offline:ver useInternalAddress:buseinternaladdress];
  1128. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1129. syncVC.action_string=@"Download";
  1130. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1131. // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1132. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1133. [parent presentViewController:navi animated:YES completion:^{
  1134. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1135. DebugLog(@"about present.........");
  1136. // self.btop = false;
  1137. // <#code#>
  1138. }];
  1139. }
  1140. else
  1141. {
  1142. NSArray* arr_order=nil;
  1143. arr_order=[OLDataProvider enumOfflineOrder];
  1144. // if(arr_order.count>0)
  1145. // {
  1146. //
  1147. // {
  1148. // SelectUploadOrderViewController * vc =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SelectUploadOrderViewController"];
  1149. // vc.returnValue = ^(NSArray* SelectedOrder){
  1150. //
  1151. // [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:SelectedOrder];
  1152. // SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1153. // syncVC.action_string=@"Download";
  1154. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1155. //
  1156. //
  1157. //
  1158. //
  1159. //
  1160. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  1161. //
  1162. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1163. // [parent presentViewController:navi animated:YES completion:^{
  1164. //
  1165. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1166. //
  1167. // DebugLog(@"about present.........");
  1168. //
  1169. // // self.btop = false;
  1170. // // <#code#>
  1171. // }];
  1172. // };
  1173. //
  1174. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc] ;
  1175. //
  1176. //
  1177. //
  1178. //
  1179. //
  1180. //
  1181. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1182. // [parent presentViewController:navi animated:YES completion:^{
  1183. //
  1184. //
  1185. // }];
  1186. // }
  1187. //
  1188. //
  1189. // }
  1190. // else
  1191. {
  1192. [self upload_offline:ver useInternalAddress:buseinternaladdress orderid:arr_order];
  1193. SyncControlPanelViewController * syncVC =[ [UIStoryboard storyboardWithName:@"OLM" bundle:nil] instantiateViewControllerWithIdentifier:@"SyncControlPanelViewController"];
  1194. syncVC.action_string=@"Download";
  1195. UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:syncVC] ;
  1196. navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  1197. [parent presentViewController:navi animated:YES completion:^{
  1198. // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  1199. DebugLog(@"about present.........");
  1200. // self.btop = false;
  1201. // <#code#>
  1202. }];
  1203. }
  1204. }
  1205. }
  1206. -(void) download_offline:(bool) start checkdiskspace:(bool) checkdiskspace
  1207. {
  1208. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeOfflineSync Action:nil Extra:nil];
  1209. if(start)
  1210. {
  1211. [ [ UIApplication sharedApplication] setIdleTimerDisabled:YES ] ;
  1212. long long size= [[self.download_task valueForKey:@"size"] longLongValue] /1024/1024;
  1213. // [self add_downloadlog:[NSString stringWithFormat:@"Total size %lldMB",size]];
  1214. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1215. long long needsize = size+500;
  1216. if(needsize>freespace &&checkdiskspace)
  1217. {
  1218. //size not enough.
  1219. NSString* space=[NSString stringWithFormat:@"Disk space not enough, need %lldMB free space at least, current free space %lldMB",needsize,freespace];
  1220. [self add_downloadlog:space];
  1221. [self.settingUI onSyncFinish];
  1222. return ;
  1223. }
  1224. NSString* temp = NSTemporaryDirectory();
  1225. NSString * ver = self.download_task[@"ver"];
  1226. NSString *tempfolder = [temp stringByAppendingPathComponent:ver];
  1227. //创建版本临时目录
  1228. NSFileManager* fileManager = [NSFileManager defaultManager];
  1229. BOOL bdir=YES;
  1230. if(! [fileManager fileExistsAtPath:tempfolder isDirectory:&bdir])
  1231. {
  1232. NSError *error = nil;
  1233. bool bsuccess=[fileManager createDirectoryAtPath:tempfolder withIntermediateDirectories:YES attributes:nil error:&error];
  1234. if(!bsuccess)
  1235. DebugLog(@"Create temp folder failed");
  1236. // if(bsuccess)
  1237. // {
  1238. // sqlite3 *db = [self get_db];
  1239. //
  1240. // [self execSql:[NSString stringWithFormat:@"insert into img_cache(name) values('%@')",name] db:db];
  1241. // [iSalesDB close_db:db];
  1242. // }
  1243. }
  1244. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/",ver];
  1245. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1246. if(! [fileManager fileExistsAtPath:imagecache isDirectory:&bdir])
  1247. {
  1248. NSError *error = nil;
  1249. bool bsuccess=[fileManager createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1250. if(!bsuccess)
  1251. DebugLog(@"Create cache folder failed");
  1252. }
  1253. NSString* resourcefolder=[NSString stringWithFormat:@"%@/offline_data/",ver];
  1254. NSString *resource = [temp stringByAppendingPathComponent:resourcefolder];
  1255. // if(! [fileManager fileExistsAtPath:resource isDirectory:&bdir])
  1256. // {
  1257. //
  1258. // NSError *error = nil;
  1259. // bool bsuccess=[fileManager createDirectoryAtPath:resource withIntermediateDirectories:YES attributes:nil error:&error];
  1260. //
  1261. // if(!bsuccess)
  1262. // DebugLog(@"Create resource folder failed");
  1263. //
  1264. // }
  1265. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1266. NSString *documents = /*[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];*/[paths objectAtIndex:0];
  1267. NSString *database_path = [documents stringByAppendingPathComponent:DBNAME];
  1268. NSString* tempdb=[NSString stringWithFormat:@"%@%@/%@",temp,ver,DBNAME];
  1269. // tempdb=[documents stringByAppendingPathComponent:DBNAME];
  1270. NSError *error = nil;
  1271. bdir=NO;
  1272. if(! [fileManager fileExistsAtPath:tempdb isDirectory:&bdir])
  1273. {
  1274. // [iSalesDB execSql:@"PRAGMA journal_mode = DELETE;"];
  1275. if(![fileManager copyItemAtPath:database_path toPath:tempdb error:&error])
  1276. {
  1277. DebugLog(@"copy database failed");
  1278. }
  1279. }
  1280. bdir=YES;
  1281. error=nil;
  1282. int count = [[self.download_task valueForKey:@"count"] intValue];
  1283. bool alldone=true;
  1284. bool trouble=false;
  1285. bool response = false;
  1286. for (int i = 0;i<count;i++)
  1287. {
  1288. NSMutableDictionary* itemjson = [[self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]] mutableCopy];
  1289. NSString* url = [itemjson valueForKey:@"url"];
  1290. NSString* type = [itemjson valueForKey:@"type"];
  1291. {
  1292. #ifdef DEBUG
  1293. //调试模式下跳过下载图片
  1294. if([type isEqualToString:@"img"])
  1295. {
  1296. itemjson[@"status"]=@"finish";
  1297. continue;
  1298. }
  1299. #endif
  1300. }
  1301. NSString* status = itemjson[@"status"];
  1302. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1303. if(! [status isEqualToString:@"finish"])
  1304. {
  1305. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1306. {
  1307. [self handle_download:url start:start type:type taskid:i];
  1308. alldone=false;
  1309. break;
  1310. }
  1311. else
  1312. {
  1313. alldone=false;
  1314. trouble=true;
  1315. response = [itemjson[@"response"] boolValue];
  1316. break;
  1317. }
  1318. }
  1319. }
  1320. if(trouble)
  1321. {
  1322. NSString* msg =@"offline sync got some trouble, sync canceled.";
  1323. if(response==false)
  1324. {
  1325. msg=@"Cannot connect to server, please check your network.";
  1326. }
  1327. [self add_downloadlog:msg];
  1328. dispatch_async(dispatch_get_main_queue(), ^{
  1329. // self.downloadlog=nil;
  1330. self.downloading=false;
  1331. });
  1332. [self.settingUI onSyncFinish];
  1333. }
  1334. else if(alldone)
  1335. {
  1336. [self add_downloadlog:@"Finalizing download..."];
  1337. //全部下载完成;
  1338. //写入当前版本
  1339. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1340. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1341. NSString* lastsync = [formatter stringFromDate:[NSDate date]];
  1342. NSString* ver= self.download_task[@"ver"];
  1343. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1344. NSString *cachefolder = [paths objectAtIndex:0];
  1345. NSString *img_cache = [cachefolder stringByAppendingPathComponent:@"img_cache"];
  1346. //NSString *cached_offline_data = [cachefolder stringByAppendingPathComponent:@"offline_data"];
  1347. if(![RAUtils mergeContentsOfPath:imagecache intoPath:img_cache error:&error])
  1348. {
  1349. DebugLog(@"move image folder failed");
  1350. [self add_downloadlog:@"move image folder failed"];
  1351. trouble=true;
  1352. }
  1353. else
  1354. {
  1355. DebugLog(@"move image folder successful");
  1356. }
  1357. error=nil;
  1358. // copy temp db to cache.
  1359. if( [fileManager fileExistsAtPath:database_path isDirectory:&bdir])
  1360. {
  1361. if(![fileManager removeItemAtPath:database_path error:nil])
  1362. {
  1363. DebugLog(@"delete database failed");
  1364. }
  1365. else
  1366. {
  1367. if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1368. {
  1369. DebugLog(@"copy database failed");
  1370. [self add_downloadlog:@"copy database failed"];
  1371. trouble=true;
  1372. }
  1373. else{
  1374. BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1375. // [iSalesDB execSql:@"PRAGMA journal_mode = WAL;"];
  1376. }
  1377. }
  1378. }
  1379. else if(![fileManager copyItemAtPath:tempdb toPath:database_path error:&error])
  1380. {
  1381. DebugLog(@"copy database failed");
  1382. BOOL blDele= [fileManager removeItemAtPath:tempdb error:nil];
  1383. [self add_downloadlog:@"copy database failed"];
  1384. trouble=true;
  1385. }
  1386. // if(![RAUtils mergeContentsOfPath:tempdb intoPath:database_path error:&error])
  1387. // {
  1388. // DebugLog(@"move db file failed");
  1389. // }
  1390. // else
  1391. // {
  1392. // DebugLog(@"move db file successful");
  1393. // }
  1394. error=nil;
  1395. if(![RAUtils mergeContentsOfPath:resource intoPath:cachefolder error:&error])
  1396. {
  1397. DebugLog(@"move data folder failed");
  1398. [self add_downloadlog:@"move data folder failed"];
  1399. trouble=true;
  1400. }
  1401. else
  1402. {
  1403. DebugLog(@"move data folder successful");
  1404. }
  1405. [ [ UIApplication sharedApplication] setIdleTimerDisabled:NO ] ;
  1406. if(trouble)
  1407. {
  1408. [self add_downloadlog:@"offline sync failed."];
  1409. // 尚缺更新失败还原逻辑。
  1410. }
  1411. else
  1412. {
  1413. [self add_downloadlog:@"offline sync complete."];
  1414. NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
  1415. [defaults removeObjectForKey:@"OfflineVer"];
  1416. [defaults setValue:ver forKey:@"OfflineVer"];
  1417. [defaults removeObjectForKey:@"LastSync"];
  1418. [defaults setValue:lastsync forKey:@"LastSync"];
  1419. [defaults removeObjectForKey:@"vid"];
  1420. [defaults setValue:self.vid forKey:@"vid"];
  1421. [defaults removeObjectForKey:@"Forcedownload"];
  1422. NSString * downSerial = [defaults valueForKey:@"downSerial"];
  1423. [defaults removeObjectForKey:@"downSerial"];
  1424. [defaults removeObjectForKey:@"OFFLINE_DIRTY"];
  1425. [defaults setBool:FALSE forKey:@"OFFLINE_DIRTY"];
  1426. [defaults synchronize];
  1427. NSString *plistPath = [RAUtils get_config_path];
  1428. NSMutableDictionary *config_list = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
  1429. if([config_list[@"NEED_FULLY_SYNC"] boolValue])
  1430. {
  1431. config_list[@"NEED_FULLY_SYNC"] = @"false";
  1432. [config_list writeToFile:plistPath atomically:YES];
  1433. }
  1434. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1435. NSDictionary* editor_json = [iSalesNetwork finish_download_Offline:downSerial];
  1436. });
  1437. }
  1438. dispatch_async(dispatch_get_main_queue(), ^{
  1439. // self.downloadlog=nil;
  1440. self.downloading=false;
  1441. self.download_task=nil;
  1442. self.vid=nil;
  1443. [self.settingUI onSyncFinish];
  1444. });
  1445. }
  1446. }
  1447. else
  1448. {
  1449. int count = [[self.download_task valueForKey:@"count"] intValue];
  1450. for (int i = 0;i<count;i++)
  1451. {
  1452. NSDictionary* itemjson = [self.download_task objectForKey:[NSString stringWithFormat:@"item_%d",i]];
  1453. NSString* url = [itemjson valueForKey:@"url"];
  1454. NSString* type = [itemjson valueForKey:@"type"];
  1455. NSString* status = itemjson[@"status"];
  1456. //bool finish = [[itemjson valueForKey:@"finish"] boolValue];
  1457. if(! [status isEqualToString:@"finish"])
  1458. {
  1459. if([itemjson[@"retry"] intValue]<DOWNLOAD_RETRY_TIMES)
  1460. {
  1461. [self handle_download:url start:start type:type taskid:i];
  1462. break;
  1463. }
  1464. }
  1465. }
  1466. dispatch_async(dispatch_get_main_queue(), ^{
  1467. self.downloading=false;
  1468. });
  1469. }
  1470. }
  1471. -(void) add_downloadlog:(NSString*) newtext
  1472. {
  1473. // if(!self.downloading)
  1474. // return;
  1475. dispatch_async(dispatch_get_main_queue(), ^{
  1476. NSString* date;
  1477. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1478. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1479. date = [formatter stringFromDate:[NSDate date]];
  1480. if(newtext.length<=0)
  1481. return;
  1482. NSString* text = self.downloadlog;
  1483. if(text.length==0)
  1484. text=@"";
  1485. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1486. self.downloadlog = text;
  1487. [self.settingUI onLogUpdate];
  1488. });
  1489. }
  1490. -(int)unpack
  1491. {
  1492. //return;
  1493. //DebugLog(_fileName);
  1494. ///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
  1495. //文件路径
  1496. // NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  1497. NSString* temp = NSTemporaryDirectory();
  1498. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1499. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@.",filename]];
  1500. NSString * ver = self.download_task[@"ver"];
  1501. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,filename];
  1502. NSString *zipFile = [temp stringByAppendingPathComponent:location];
  1503. ZipArchive* zip = [[ZipArchive alloc] init];
  1504. // filename stringByDeletingPathExtension
  1505. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  1506. // NSString *cachefolder = [paths objectAtIndex:0];
  1507. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1508. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1509. //
  1510. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1511. // NSString *documentPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
  1512. //NSString* zipFile = [documentPath stringByAppendingString:@"/images.zip"] ;
  1513. // NSString* unZipTo = img_cache;//[documentPath stringByAppendingString:@"/images"] ;
  1514. DebugLog(@"path: %@",unZipTo);
  1515. if( [zip UnzipOpenFile:zipFile Password:@"#UL$dc01"] ){
  1516. BOOL result = [zip UnzipFileTo:unZipTo overWrite:YES];
  1517. if( NO==result )
  1518. {
  1519. // int aaa=0;
  1520. //解压失败
  1521. long long freespace=[RAUtils freeDiskSpaceInMegaBytes];
  1522. if(freespace<=10)
  1523. {
  1524. return UNZIP_NO_SPACE;
  1525. }
  1526. [zip UnzipCloseFile];
  1527. //文件损坏,删除文件重试
  1528. NSFileManager* fileManager=[NSFileManager defaultManager];
  1529. BOOL blDele= [fileManager removeItemAtPath:zipFile error:nil];
  1530. [fileManager removeItemAtPath:unZipTo error:nil];
  1531. return UNZIP_FILE_DAMAGE;
  1532. }
  1533. else
  1534. {
  1535. [zip UnzipCloseFile];
  1536. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ successful.",filename]];
  1537. NSFileManager *fileManager = [NSFileManager defaultManager];
  1538. [fileManager removeItemAtPath:zipFile error:nil];
  1539. return UNZIP_SUCCESS;
  1540. //NSString *imageDir = [NSString stringWithFormat:@"%@/Caches/%@", NSHomeDirectory(), dirName];
  1541. }
  1542. //[zip UnzipCloseFile];
  1543. }
  1544. else
  1545. {
  1546. //打开文件失败,通常是文件路径有问题或密码错误。
  1547. return UNZIP_OPEN_FAILED;
  1548. NSFileManager *fileManager = [NSFileManager defaultManager];
  1549. [fileManager removeItemAtPath:zipFile error:nil];
  1550. }
  1551. // [zip release];
  1552. }
  1553. #pragma mark - NSURLConnectionDelegate
  1554. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  1555. DebugLog(@"%d error message:%@",self.current_task,error);
  1556. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1557. // self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] = [NSNumber numberWithLongLong:0];
  1558. currenttask[@"status"] = @"pause";
  1559. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1560. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1561. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1562. // self.currentLength = 0;
  1563. // self.fileLength = 0;
  1564. [self.fileHandle closeFile];
  1565. self.fileHandle = nil;
  1566. [self.connection cancel];
  1567. self.connection = nil;
  1568. [self download_offline:true checkdiskspace:false];
  1569. }
  1570. #pragma mark - NSURLConnectionDataDelegate
  1571. /**
  1572. *请求失败
  1573. */
  1574. /**
  1575. *接收到服务器的响应
  1576. */
  1577. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  1578. NSHTTPURLResponse* httpresponse = (NSHTTPURLResponse *)response;
  1579. if (httpresponse.statusCode == 206) {//!!!断点续传的状态码为206
  1580. DebugLog(@"%d begin",self.current_task);
  1581. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1582. //获取下载文件大小
  1583. // self.fileLength = response.expectedContentLength;
  1584. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1585. //获取文件名
  1586. //self.fileName = response.suggestedFilename;
  1587. currenttask[@"fileName"] = response.suggestedFilename;
  1588. currenttask[@"response"] = @"true";
  1589. [self add_downloadlog:[NSString stringWithFormat:@"Begin download file %@.",currenttask[@"fileName"]]];
  1590. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1591. //文件路径
  1592. NSString *temp = NSTemporaryDirectory();//[NSSearchPathForDirectoriesInDomains(NSTemporaryDirectory(), NSUserDomainMask, YES) lastObject];
  1593. NSString * ver = self.download_task[@"ver"];
  1594. NSString* location=[NSString stringWithFormat:@"%@/%@",ver,response.suggestedFilename];
  1595. NSString *filePath = [temp stringByAppendingPathComponent:location];
  1596. DebugLog(@"save to: %@",filePath);
  1597. if (position>0) {
  1598. //不需要创建文件;
  1599. //创建一个用来写数据的文件句柄
  1600. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1601. return;
  1602. }
  1603. // 第一次获取的才是文件正确大小
  1604. currenttask[@"fileLength"] = [NSNumber numberWithLongLong:response.expectedContentLength];
  1605. //创建一个空的文件到沙盒
  1606. NSFileManager *fileManager = [NSFileManager defaultManager];
  1607. [fileManager createFileAtPath:filePath contents:nil attributes:nil];
  1608. //创建一个用来写数据的文件句柄
  1609. self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
  1610. }else{
  1611. //debug 这里缺少文件的情况还没处理
  1612. [self.connection cancel];
  1613. self.connection = nil;
  1614. DebugLog(@"该文件不存在");
  1615. NSString* str_status=[NSString stringWithFormat:@"Server return %d.",httpresponse.statusCode];
  1616. [self add_downloadlog:@"Offline file does not exist,please contact your administrator."];
  1617. [self add_downloadlog:str_status];
  1618. }
  1619. }
  1620. /**
  1621. *接收到服务器返回的数据(可能被调用多次)
  1622. */
  1623. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  1624. //移动到文件末尾
  1625. [self.fileHandle seekToEndOfFile];
  1626. //写入数据到文件
  1627. [self.fileHandle writeData:data];
  1628. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1629. long long position=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"position"] longLongValue];
  1630. position += data.length;
  1631. currenttask[@"position"] = [NSNumber numberWithLongLong:position];
  1632. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1633. //更新画面中的进度
  1634. int fileLength=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileLength"] intValue];
  1635. double progress = (double)position/fileLength;
  1636. self.file_progress = progress;
  1637. [self.settingUI onProgressUpdate];
  1638. }
  1639. /**
  1640. *服务器返回数据完了
  1641. */
  1642. - (void)connectionDidFinishLoading:(NSURLConnection *)connection{
  1643. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1644. [self add_downloadlog:[NSString stringWithFormat:@"Finish download file %@.",currenttask[@"fileName"]]];
  1645. DebugLog(@"%d finish",self.current_task);
  1646. currenttask[@"position"] = [NSNumber numberWithLongLong:0];
  1647. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1648. // self.currentLength = 0;
  1649. // self.fileLength = 0;
  1650. [self.fileHandle closeFile];
  1651. self.fileHandle = nil;
  1652. int result=[self unpack];
  1653. NSString* temp = NSTemporaryDirectory();
  1654. NSString* filename = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"fileName"];
  1655. NSString * ver = self.download_task[@"ver"];
  1656. NSString* unziplocation=[NSString stringWithFormat:@"%@/%@",ver,[filename stringByDeletingPathExtension]];
  1657. NSString *unZipTo = [temp stringByAppendingPathComponent:unziplocation];
  1658. switch (result) {
  1659. case UNZIP_FILE_DAMAGE:
  1660. {
  1661. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1662. currenttask[@"status"] = @"pause";
  1663. int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1664. currenttask[@"retry"]= [NSNumber numberWithInt:retry+1];
  1665. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1666. // self.currentLength = 0;
  1667. // self.fileLength = 0;
  1668. [self.fileHandle closeFile];
  1669. self.fileHandle = nil;
  1670. [self.connection cancel];
  1671. self.connection = nil;
  1672. break;
  1673. }
  1674. case UNZIP_SUCCESS:
  1675. {
  1676. NSString* type = self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"type"];
  1677. if([type isEqualToString:@"img"])
  1678. {
  1679. NSString* parent_path = self.download_task[@"path"];
  1680. if(parent_path.length==0)
  1681. parent_path=@"";
  1682. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"http://" withString:@""];
  1683. parent_path = [parent_path stringByReplacingOccurrencesOfString:@"https://" withString:@""];
  1684. NSString* cachefolder=[NSString stringWithFormat:@"%@/image_cache/%@",ver,parent_path];
  1685. NSString *imagecache = [temp stringByAppendingPathComponent:cachefolder];
  1686. BOOL bdir=YES;
  1687. NSError *error = nil;
  1688. if(! [[NSFileManager defaultManager] fileExistsAtPath:imagecache isDirectory:&bdir])
  1689. {
  1690. bool bsuccess=[[NSFileManager defaultManager] createDirectoryAtPath:imagecache withIntermediateDirectories:YES attributes:nil error:&error];
  1691. if(!bsuccess)
  1692. DebugLog(@"Create temp folder failed");
  1693. }
  1694. error=nil;
  1695. // NSString* backupfolder=[NSString stringWithFormat:@"%@/test.xml",ver];
  1696. // NSString* backup=[temp stringByAppendingPathComponent:backupfolder];
  1697. // NSError *error = nil;
  1698. // NSURL* uf=[NSURL fileURLWithPath:imagecache];
  1699. // if( [[NSFileManager defaultManager] replaceItemAtURL:[NSURL fileURLWithPath:imagecache]
  1700. // withItemAtURL:[NSURL fileURLWithPath:unZipTo]
  1701. // backupItemName:backup
  1702. // options:NSFileManagerItemReplacementWithoutDeletingBackupItem
  1703. // resultingItemURL:nil error:&error])
  1704. if(![RAUtils mergeContentsOfPath:unZipTo intoPath:imagecache error:&error])
  1705. // if([[NSFileManager defaultManager] moveItemAtPath:unZipTo toPath:imagecache error:&error]!=YES)// prePath 为原路径、 cenPath 为目标路径
  1706. {
  1707. DebugLog(@"move image folder failed");
  1708. }
  1709. else
  1710. {
  1711. currenttask[@"status"] = @"finish";
  1712. DebugLog(@"move image folder successful");
  1713. }
  1714. }
  1715. else if([type isEqualToString:@"sql"])
  1716. {
  1717. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  1718. NSString * ver = self.download_task[@"ver"];
  1719. NSString* tempdb=[NSString stringWithFormat:@"%@/%@",ver,DBNAME];
  1720. tempdb=[temp stringByAppendingPathComponent:tempdb];
  1721. sqlite3* tdb=[iSalesDB get_db_at:tempdb];
  1722. [self add_downloadlog:@"updating local database..."];
  1723. @try {
  1724. char *errmsg=NULL;
  1725. appDelegate.disable_trigger=true;
  1726. if (sqlite3_exec(tdb, "begin", NULL, NULL, &errmsg)==SQLITE_OK)
  1727. {
  1728. 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;offline_pdf;", NULL, NULL, &errmsg);
  1729. sqlite3_free(errmsg);
  1730. DebugLog(@"开启事务");
  1731. NSString* jsonpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,@"SqlJson.txt"];
  1732. NSDictionary* orderjson=[RAUtils dictfromfile:jsonpath];
  1733. int count = [orderjson[@"count"] intValue];
  1734. for(int i=0;i<count;i++)
  1735. {
  1736. NSString* sqlfile=orderjson[[NSString stringWithFormat:@"item_%d",i]];
  1737. NSString* sqlpath =[NSString stringWithFormat:@"%@/offLineSql/%@",unZipTo,sqlfile];
  1738. NSError *error = nil;
  1739. NSString* sql = [NSString stringWithContentsOfFile:sqlpath encoding:NSUTF8StringEncoding error:&error];
  1740. //DebugLog(@"NSString类方法读取的内容是:\n%@",content);
  1741. if(sqlite3_exec(tdb, [sql UTF8String], NULL, NULL, &errmsg)!=SQLITE_OK)
  1742. {
  1743. //throw exception;
  1744. if(errmsg==nil)
  1745. errmsg="Unknown error.";
  1746. NSString *nsmsg = [[NSString alloc]initWithUTF8String:errmsg];
  1747. [NSException raise:@"offline update sql error" format:@"FILE:%@ MSG:%@",sqlfile,nsmsg];
  1748. }
  1749. sqlite3_free(errmsg);
  1750. }
  1751. 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);
  1752. }
  1753. //提交事务
  1754. if (sqlite3_exec(tdb, "commit", NULL, NULL, &errmsg)==SQLITE_OK) {
  1755. DebugLog(@"提交事务");
  1756. sqlite3_free(errmsg);
  1757. }
  1758. [self add_downloadlog:@"updating local database successful"];
  1759. currenttask[@"status"] = @"finish";
  1760. }
  1761. @catch (NSException *exception) {
  1762. char *errmsg=NULL;
  1763. [self add_downloadlog:[NSString stringWithFormat:@"updating local database error, %@",exception.description]];
  1764. [self add_downloadlog:@"updating local database failed rollback..."];
  1765. if (sqlite3_exec(tdb, "rollback", NULL, NULL, &errmsg)==SQLITE_OK) {
  1766. DebugLog(@"回滚事务");
  1767. }
  1768. else
  1769. {
  1770. [self add_downloadlog:@"rollback failed."];
  1771. }
  1772. NSMutableDictionary* currenttask=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]] mutableCopy];
  1773. currenttask[@"status"] = @"pause";
  1774. //int retry=[self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]][@"retry"] intValue];
  1775. currenttask[@"retry"]= [NSNumber numberWithInt:DOWNLOAD_RETRY_TIMES];
  1776. self.download_task [[NSString stringWithFormat:@"item_%d",self.current_task]]=currenttask;
  1777. // self.currentLength = 0;
  1778. // self.fileLength = 0;
  1779. [self.fileHandle closeFile];
  1780. self.fileHandle = nil;
  1781. [self.connection cancel];
  1782. self.connection = nil;
  1783. //break;
  1784. }
  1785. @finally {
  1786. appDelegate.disable_trigger=false;
  1787. sqlite3_close(tdb);
  1788. // [iSalesDB close_db:tdb];
  1789. // [self SelectData];
  1790. }
  1791. }
  1792. else if([type isEqualToString:@"script"])
  1793. {
  1794. currenttask[@"status"] = @"finish";
  1795. }
  1796. else if([type isEqualToString:@"resource"])
  1797. {
  1798. currenttask[@"status"] = @"finish";
  1799. }
  1800. int c=self.current_task+1;
  1801. double t=[ self.download_task[@"count"] doubleValue];
  1802. double oprogress=(self.current_task+1) / [ self.download_task[@"count"] doubleValue];
  1803. self.overall_progress = oprogress;
  1804. [self.settingUI onProgressUpdate];
  1805. break;
  1806. }
  1807. case UNZIP_NO_SPACE:
  1808. {
  1809. [self add_downloadlog:@"Disk space not enough."];
  1810. break;
  1811. }
  1812. case UNZIP_OPEN_FAILED:
  1813. {
  1814. [self add_downloadlog:[NSString stringWithFormat:@"Unpack file %@ failed, error: cannot unpack zip.",filename]];
  1815. break;
  1816. }
  1817. default:
  1818. break;
  1819. }
  1820. [self download_offline:true checkdiskspace:false];
  1821. }
  1822. #pragma mark - Scaner
  1823. -(void)onTimer: (NSTimer*)theTimer{
  1824. if(theTimer==ScanApiConsumer){
  1825. // [self addlog:@"ScanApi::doScanApiReceive:"];
  1826. [ScanApi doScanApiReceive];
  1827. }
  1828. }
  1829. -(void) addlog:(NSString*) newtext
  1830. {
  1831. if(!self.enable_ScannerLog)
  1832. return;
  1833. dispatch_async(dispatch_get_main_queue(), ^{
  1834. NSString* date;
  1835. NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
  1836. [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
  1837. date = [formatter stringFromDate:[NSDate date]];
  1838. if(newtext.length<=0)
  1839. return;
  1840. NSString* text = self.log;
  1841. if(text.length==0)
  1842. text=@"";
  1843. text = [NSString stringWithFormat:@"%@%@----------%@\n",text,date,newtext];
  1844. self.log = text;
  1845. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  1846. [avc onLogUpdate];
  1847. });
  1848. }
  1849. - (void)enableScanner:(bool)enable {
  1850. [self addlog:@"Enable scanner:"];
  1851. if(enable)
  1852. {
  1853. [self addlog:@"Enable"];
  1854. self.api_Status = API_INIT;
  1855. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  1856. self.Status_Text = @"Initialize...";
  1857. [avc onStatusChanged:@"Initialize..."];
  1858. [ScanApi open];
  1859. [self addlog:@"ScanApi open"];
  1860. ScanApiConsumer=[NSTimer scheduledTimerWithTimeInterval:.2 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
  1861. [self addlog:@"ScanApiConsumer init"];
  1862. // [ScanApi close];
  1863. // [self addlog:@"ScanApi opent"];
  1864. }
  1865. else
  1866. {
  1867. [self addlog:@"Disable"];
  1868. // [ScanApiConsumer invalidate];
  1869. // ScanApiConsumer= nil;
  1870. // [self addlog:@"ScanApiConsumer invalidate"];
  1871. self.api_Status = API_CLOSING;
  1872. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  1873. self.Status_Text = @"Stoping...";
  1874. [avc onStatusChanged:@"Stoping..."];
  1875. [ScanApi close];
  1876. [self addlog:@"ScanApi close"];
  1877. }
  1878. }
  1879. #pragma mark - Device Info List management
  1880. -(void) updateDevicesList:(DeviceInfo*) deviceInfo Add:(BOOL)add{
  1881. [self addlog:@"updateDevicesList:"];
  1882. if(add==YES){
  1883. [self.devices addObject:deviceInfo];
  1884. }
  1885. else{
  1886. [self.devices removeObject:deviceInfo];
  1887. }
  1888. NSMutableString* temp=[[NSMutableString alloc]init];
  1889. for (DeviceInfo* info in self.devices) {
  1890. [temp appendString:[info getName]];
  1891. [temp appendString:@"\n"];
  1892. }
  1893. if(self.devices.count>0)
  1894. [temp appendString:@"ready to scan"];
  1895. else
  1896. [temp appendString:@"Waiting for Scanner..."];
  1897. // _Status.text=temp ;
  1898. [self addlog:temp];
  1899. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  1900. self.Status_Text = temp;
  1901. [avc onStatusChanged:temp];
  1902. [avc OnUpdateDevicesList];
  1903. // if ([self.active_controller respondsToSelector:@selector(lockPortrait)])
  1904. // [self.dev_table reloadData];
  1905. }
  1906. #pragma mark - ScanApiHelper complete delegates
  1907. // THE 2 FOLLOWING CALLBACKS ARE FOR DEMO ONLY FOR SHOWING HOW
  1908. // TO CHECK IF A SYMBOLOGY IS ALREADY ENABLED AND IF NOT IT ENABLES
  1909. // IT RIGHT THERE. THE GOAL IS TO CONFIGURE ONCE THE SCANNER WHEN IT
  1910. // CONNECTS TO THE DEVICE. IF THERE IS NO SPECIFIC NEED TO CONFIGURE
  1911. // THE SCANNER, THESE CALLBACKS CAN BE REMOVED
  1912. // callback received when the Get Symbology Status is completed
  1913. -(void)onGetSymbologyDpm:(ISktScanObject*)scanObj{
  1914. [self addlog:@"onGetSymbologyDpm:"];
  1915. SKTRESULT result=[[scanObj Msg]Result];
  1916. if(SKTSUCCESS(result)){
  1917. DeviceInfo* deviceInfo=[ScanApi getDeviceInfoFromScanObject:scanObj];
  1918. if(deviceInfo!=nil){
  1919. ISktScanSymbology* symbology=[[scanObj Property]Symbology];
  1920. if([symbology getStatus]==kSktScanSymbologyStatusDisable){
  1921. [ScanApi postSetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Status:TRUE Target:self Response:@selector(onSetSymbology:)];
  1922. }
  1923. }
  1924. }
  1925. else{
  1926. // an error message should be displayed here
  1927. // indicating that the DPM symbology status cannot be retrieved
  1928. }
  1929. }
  1930. // callback received when the Set Symbology Status is completed
  1931. -(void)onSetSymbology:(ISktScanObject*)scanObj{
  1932. [self addlog:@"onSetSymbology:"];
  1933. SKTRESULT result=[[scanObj Msg]Result];
  1934. if(!SKTSUCCESS(result)){
  1935. // display an error message saying a symbology cannot be set
  1936. }
  1937. }
  1938. /**
  1939. *
  1940. */
  1941. -(void) onSetDataConfirmationMode:(ISktScanObject*)scanObj{
  1942. [self addlog:@"onSetDataConfirmationMode:"];
  1943. SKTRESULT result=[[scanObj Msg]Result];
  1944. if(SKTSUCCESS(result)){
  1945. [self addlog:@"DataConfirmation Mode OK"];
  1946. }
  1947. else{
  1948. [self addlog:[NSString stringWithFormat:@"DataConfirmation Mode Error %ld",result]];
  1949. }
  1950. }
  1951. /**
  1952. *
  1953. */
  1954. -(void) onDataConfirmation:(ISktScanObject*)scanObj{
  1955. [self addlog:@"onDataConfirmation:"];
  1956. SKTRESULT result=[[scanObj Msg]Result];
  1957. if(SKTSUCCESS(result)){
  1958. [self addlog:@"Data Confirmed OK"];
  1959. }
  1960. else{
  1961. [self addlog:[NSString stringWithFormat:@"Data Confirmed Error %ld",result]];
  1962. }
  1963. }
  1964. /**
  1965. *
  1966. */
  1967. -(void) onSetLocalDecodeAction:(ISktScanObject*)scanObj{
  1968. [self addlog:@"onSetLocalDecodeAction:"];
  1969. SKTRESULT result=[[scanObj Msg]Result];
  1970. if(SKTSUCCESS(result)){
  1971. [self addlog:@"Local Decode Action OK"];
  1972. }
  1973. else{
  1974. [self addlog:[NSString stringWithFormat:@"Local Decode Action Error %ld",result]];
  1975. }
  1976. }
  1977. /**
  1978. *
  1979. */
  1980. -(void) onGetSoftScanStatus:(ISktScanObject*)scanObj{
  1981. SKTRESULT result=[[scanObj Msg]Result];
  1982. if(SKTSUCCESS(result)){
  1983. ISktScanProperty* property=[scanObj Property];
  1984. [self addlog:@"SoftScan status:"];
  1985. if([property getByte]==kSktScanEnableSoftScan){
  1986. [self addlog:@"SoftScan is ENABLED"];
  1987. _softScannerEnabled=TRUE;
  1988. }
  1989. else{
  1990. _softScannerEnabled=FALSE;
  1991. [self addlog:@"SoftScan is DISABLED"];
  1992. }
  1993. }
  1994. else{
  1995. [self addlog:[ NSString stringWithFormat:@"getting SoftScanStatus returned the error %ld",result]];
  1996. }
  1997. }
  1998. /**
  1999. *
  2000. */
  2001. -(void) onSetSoftScanStatus:(ISktScanObject*)scanObj{
  2002. [self addlog:@"onSetSoftScanStatus:"];
  2003. SKTRESULT result=[[scanObj Msg]Result];
  2004. if(SKTSUCCESS(result)){
  2005. [self addlog:@"SoftScan set status success"];
  2006. }
  2007. else{
  2008. [self addlog:[NSString stringWithFormat:@"SoftScan set status returned the error %ld",result]];
  2009. }
  2010. }
  2011. /**
  2012. *
  2013. */
  2014. -(void) onSetTrigger:(ISktScanObject*)scanObj{
  2015. [self addlog:@"onSetTrigger:"];
  2016. SKTRESULT result=[[scanObj Msg]Result];
  2017. if(SKTSUCCESS(result)){
  2018. [self addlog:@"Trigger set success"];
  2019. }
  2020. else{
  2021. [self addlog:[NSString stringWithFormat:@"Trigger set returned the error %ld",result]];
  2022. }
  2023. }
  2024. /**
  2025. *
  2026. */
  2027. -(void) onGetScanApiVersion:(ISktScanObject*)scanObj{
  2028. [self addlog:@"onGetScanApiVersion:"];
  2029. SKTRESULT result=[[scanObj Msg]Result];
  2030. if(SKTSUCCESS(result))
  2031. {
  2032. ISktScanProperty*property=[scanObj Property];
  2033. if([property getType]==kSktScanPropTypeVersion)
  2034. {
  2035. scanApiVersion=[NSString stringWithFormat:@"%lx.%lx.%lx.%ld",
  2036. [[property Version]getMajor],
  2037. [[property Version]getMiddle],
  2038. [[property Version]getMinor],
  2039. [[property Version]getBuild]];
  2040. }
  2041. }
  2042. else{
  2043. scanApiVersion=[NSString stringWithFormat:@"Get ScanAPI version Error: %ld",result];
  2044. }
  2045. [self addlog:[NSString stringWithFormat:@"ver: %@",scanApiVersion]];
  2046. }
  2047. /**
  2048. *
  2049. */
  2050. #ifdef USE_SOFTSCAN
  2051. -(void) onSetOverlayView:(ISktScanObject*)scanObj{
  2052. SKTRESULT result=[[scanObj Msg]Result];
  2053. if(SKTSUCCESS(result)){
  2054. [self addlog:@"Overlay view set success"];
  2055. }
  2056. else{
  2057. [self addlog:[NSString stringWithFormat:@"Overlay view set returned the error %ld",result]];
  2058. }
  2059. }
  2060. #endif
  2061. /**
  2062. * called each time a device connects to the host
  2063. * @param result contains the result of the connection
  2064. * @param newDevice contains the device information
  2065. */
  2066. -(void)onDeviceArrival:(SKTRESULT)result device:(DeviceInfo*)deviceInfo{
  2067. [self addlog:@"onDeviceArrival:"];
  2068. [self updateDevicesList:deviceInfo Add:YES];
  2069. #ifdef USE_SOFTSCAN
  2070. // if the scanner is a SoftScan scanner
  2071. if([deviceInfo.getTypeString compare:@"SoftScan"]==NSOrderedSame){
  2072. // _softScannerTriggerBtn.hidden=NO;
  2073. _softScanDeviceInfo=deviceInfo;
  2074. if(_deviceInfoToTrigger==nil)
  2075. _deviceInfoToTrigger=deviceInfo;
  2076. NSMutableDictionary* overlayParameter=[[NSMutableDictionary alloc]init];
  2077. [overlayParameter setValue:self forKey:[NSString stringWithCString:kSktScanSoftScanContext encoding:NSASCIIStringEncoding]];
  2078. [ScanApi postSetOverlayView:deviceInfo OverlayView:overlayParameter Target:self Response:@selector(onSetOverlayView:)];
  2079. }
  2080. else
  2081. #endif
  2082. {
  2083. if([deviceInfo.getTypeString compare:@"CHS 8Ci Scanner"]==NSOrderedSame){
  2084. // _softScannerTriggerBtn.hidden=NO;
  2085. _deviceInfoToTrigger=deviceInfo;
  2086. }
  2087. if(_doAppDataConfirmation==YES){
  2088. // switch the comment between the 2 following lines for handling the
  2089. // data confirmation beep from the scanner (local)
  2090. // if none is set, the scanner will beep only once when SingleEntry actually
  2091. // confirm the decoded data, otherwise the scanner will beep twice, one locally,
  2092. // and one when SingleEntry will confirm the decoded data
  2093. [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionNone Target:self Response:@selector(onSetLocalDecodeAction:)];
  2094. // [ScanApi postSetDecodeAction:deviceInfo DecodeAction:kSktScanLocalDecodeActionBeep|kSktScanLocalDecodeActionFlash|kSktScanLocalDecodeActionRumble Target:self Response:@selector(onSetLocalDecodeAction:)];
  2095. }
  2096. // for demonstration only, let's make sure the DPM is enabled
  2097. // first interrogate the scanner to see if it's already enabled
  2098. // and in the onGetSymbologyDpm callback, if the DPM is not already set
  2099. // then we send a Symbology property to enable it.
  2100. [ScanApi postGetSymbologyInfo:deviceInfo SymbologyId:kSktScanSymbologyDirectPartMarking Target:self Response:@selector(onGetSymbologyDpm:)];
  2101. }
  2102. }
  2103. /**
  2104. * called each time a device disconnect from the host
  2105. * @param deviceRemoved contains the device information
  2106. */
  2107. -(void) onDeviceRemoval:(DeviceInfo*) deviceRemoved{
  2108. [self addlog:@"onDeviceRemoval:"];
  2109. [self updateDevicesList:deviceRemoved Add:NO];
  2110. if(_deviceInfoToTrigger==deviceRemoved){
  2111. _deviceInfoToTrigger=nil;
  2112. }
  2113. #ifdef USE_SOFTSCAN
  2114. if(_softScanDeviceInfo==deviceRemoved){
  2115. _softScanDeviceInfo=nil;
  2116. }
  2117. if(_deviceInfoToTrigger==nil)
  2118. _deviceInfoToTrigger=_softScanDeviceInfo;
  2119. #endif
  2120. if(_deviceInfoToTrigger==nil){
  2121. // _softScannerTriggerBtn.hidden=YES;
  2122. }
  2123. }
  2124. /**
  2125. * called each time ScanAPI is reporting an error
  2126. * @param result contains the error code
  2127. */
  2128. -(void) onError:(SKTRESULT) result{
  2129. [self addlog:@"onError:"];
  2130. [self addlog:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2131. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2132. [avc onErrorInfo:[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result]];
  2133. // _Status.text=[NSString stringWithFormat:@"ScanAPI is reporting an error: %ld",result];
  2134. }
  2135. /**
  2136. * called each time ScanAPI receives decoded data from scanner
  2137. * @param deviceInfo contains the device information from which
  2138. * the data has been decoded
  2139. * @param decodedData contains the decoded data information
  2140. */
  2141. -(void) onDecodedDataResult:(long)result device:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2142. [self addlog:@"onDecodedDataResult:"];
  2143. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2144. if(SKTSUCCESS(result)){
  2145. NSString *cleanString = [[NSString stringWithUTF8String:(const char *)[decodedData getData]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  2146. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2147. [avc onDecodedData:cleanString];
  2148. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2149. [self addlog:[NSString stringWithUTF8String:(const char *)[decodedData getData]]];
  2150. if(_doAppDataConfirmation==YES){
  2151. [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2152. }
  2153. }
  2154. }
  2155. -(void) test_onDecodedDataResult:(NSString*) value
  2156. {
  2157. [self addlog:@"onDecodedDataResult:"];
  2158. //-(void) onDecodedData:(DeviceInfo *)device decodedData:(ISktScanDecodedData*)decodedData{
  2159. if(true){
  2160. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2161. [avc onDecodedData:value];
  2162. //_Entry.text=[NSString stringWithUTF8String:(const char *)[decodedData getData]];
  2163. [self addlog:value];
  2164. // if(_doAppDataConfirmation==YES){
  2165. // [ScanApi postSetDataConfirmation:device Target:self Response:@selector(onDataConfirmation:)];
  2166. // }
  2167. }
  2168. }
  2169. //-(void) didRotated
  2170. //{
  2171. //
  2172. //}
  2173. /**
  2174. * called when ScanAPI initialization has been completed
  2175. * @param result contains the initialization result
  2176. */
  2177. -(void) onScanApiInitializeComplete:(SKTRESULT) result{
  2178. [self addlog:@"onScanApiInitializeComplete:"];
  2179. if(SKTSUCCESS(result))
  2180. {
  2181. self.api_Status = API_START;
  2182. NSString* strlog =[NSString stringWithFormat:@"onScanApiInitialize SUCCESS result:%ld",result];
  2183. [self addlog:strlog];
  2184. #ifdef USE_SOFTSCAN
  2185. // make sure we support SoftScan
  2186. [ScanApi postSetSoftScanStatus:kSktScanSoftScanSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2187. // check if SoftScan is enabled
  2188. [ScanApi postGetSoftScanStatus:self Response:@selector(onGetSoftScanStatus:)];
  2189. #else
  2190. // disable support SoftScan (Default, not really needed if it was never activated)
  2191. [ScanApi postSetSoftScanStatus:kSktScanSoftScanNotSupported Target:self Response:@selector(onSetSoftScanStatus:)];
  2192. #endif
  2193. // ask for ScanAPI version (not a requirement but always nice to know)
  2194. [ScanApi postGetScanApiVersion:self Response:@selector(onGetScanApiVersion:)];
  2195. // configure ScanAPI for doing App Data confirmation,
  2196. // if TRUE then SingleEntry will confirm the decoded data
  2197. if(_doAppDataConfirmation==YES){
  2198. [ScanApi postSetConfirmationMode:kSktScanDataConfirmationModeApp Target:self Response:@selector(onSetDataConfirmationMode:)];
  2199. }
  2200. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2201. [avc onStatusChanged:@"Waiting for scanner..."];
  2202. self.Status_Text = @"Waiting for scanner...";
  2203. // _Status.text=@"Waiting for scanner...";
  2204. }
  2205. else{
  2206. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2207. [avc onStatusChanged:[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result]];
  2208. self.Status_Text =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2209. // _Status.text=[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2210. NSString* strlog =[NSString stringWithFormat:@"Error initializing ScanAPI:%ld",result];
  2211. [self addlog:strlog];
  2212. }
  2213. }
  2214. /**
  2215. * called when ScanAPI has been terminated. This will be
  2216. * the last message received from ScanAPI
  2217. */
  2218. -(void) onScanApiTerminated{
  2219. [self addlog:@"onScanApiTerminated:"];
  2220. [ScanApiConsumer invalidate];
  2221. ScanApiConsumer= nil;
  2222. [self addlog:@"ScanApiConsumer invalidate"];
  2223. self.api_Status = API_STOP;
  2224. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2225. [avc onStatusChanged:@"Off"];
  2226. self.Status_Text =@"Off";
  2227. // _Status.text = @"Off";
  2228. }
  2229. /**
  2230. * called when an error occurs during the retrieval
  2231. * of a ScanObject from ScanAPI.
  2232. * @param result contains the retrieval error code
  2233. */
  2234. -(void) onErrorRetrievingScanObject:(SKTRESULT) result{
  2235. [self addlog:@"onErrorRetrievingScanObject:"];
  2236. [self addlog:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2237. //_Status.text=[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result];
  2238. ActiveViewController* avc=(ActiveViewController*)self.active_controller;
  2239. [avc onErrorInfo:[NSString stringWithFormat:@"Error retrieving ScanObject:%ld",result]];
  2240. }
  2241. -(void) printPdf:(NSString*) url company:(NSString*)company send_to:(NSString*)send_to soid:(NSString*)soid content:(NSString*)content
  2242. {
  2243. RAPDFViewController *ViewController = [self.main_vc.storyboard instantiateViewControllerWithIdentifier:@"RAPDFViewController"];
  2244. ViewController.url = url;
  2245. ViewController.canSave = false;
  2246. ViewController.mail_content = content;
  2247. if(soid==nil)
  2248. soid =@"";
  2249. if(company==nil)
  2250. company =@"";
  2251. ViewController.save_name =soid;
  2252. NSMutableArray* arrsend_to = [[NSMutableArray alloc]init];
  2253. if(send_to.length>0)
  2254. {
  2255. arrsend_to=[[send_to componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2256. // customer_email compo
  2257. // [send_to addObject:customer_email];
  2258. }
  2259. ViewController.mail_to = arrsend_to;
  2260. #ifdef BUILD_NPD
  2261. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from NEW PACIFIC DIRECT,INC.",company,soid];//[arr_subject componentsJoinedByString:@" : "];
  2262. if (self.user_type == USER_ROLE_CUSTOMER && ![Singleton sharedInstance].currentOrderIsMerged) {
  2263. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2264. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2265. }
  2266. #endif
  2267. #ifdef BUILD_HOMER
  2268. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from HOMELEGANCE LA, INC.",company,soid];//[arr_subject componentsJoinedByString:@" : "];
  2269. if (self.user_type == USER_ROLE_CUSTOMER && ![Singleton sharedInstance].currentOrderIsMerged) {
  2270. NSString *companyName = [self.customerInfo objectForKey:@"customer_name"];
  2271. subject=[NSString stringWithFormat:@"%@ -- SO# %@ from %@",company,soid,companyName];
  2272. }
  2273. #endif
  2274. #ifdef BUILD_HMLG
  2275. NSString* subject=[NSString stringWithFormat:@"%@ -- SO# %@ from Homelegance.",company,soid];
  2276. #endif
  2277. ViewController.mail_subject = subject;
  2278. // NSString* subject;
  2279. // if (company.length==0) {
  2280. // NSString* cur_time =[RAUtils current_date];
  2281. // subject =name;//[NSString stringWithFormat:@"NPD Product List %@",cur_time];
  2282. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  2283. // NSString* customer_email= [appDelegate.customerInfo valueForKey:@"customer_email"];
  2284. //
  2285. //
  2286. // NSMutableArray* send_to = [[NSMutableArray alloc]init];
  2287. // if(customer_email.length>0)
  2288. // {
  2289. // send_to=[[customer_email componentsSeparatedByString:NSLocalizedString(@";", nil)] mutableCopy];
  2290. // // customer_email compo
  2291. // // [send_to addObject:customer_email];
  2292. // }
  2293. // ViewController.mail_to = send_to;
  2294. // }
  2295. // else
  2296. // {
  2297. // subject = [NSString stringWithFormat:@"Tear sheet for %@",company ];
  2298. // }
  2299. // ViewController.attachment_name = [NSString stringWithFormat:@"NPD_Product_List %@.pdf",cur_time];
  2300. // ViewController.mail_subject = subject;
  2301. ViewController.autoPrint=true;
  2302. ViewController.hidenavi = false;
  2303. [self.main_vc.navigationController pushViewController:ViewController animated:YES];
  2304. // [ViewController.navigationController setNavigationBarHidden:NO animated:NO];
  2305. }
  2306. @end