// // PDFViewController.m // RedAnt ERP Mobile // // Created by Ray on 14-8-7. // Copyright (c) 2014年 United Software Applications, Inc. All rights reserved. // #import "PDFViewController.h" #import "RAUtils.h" #import "const.h" @interface PDFViewController () @end @implementation PDFViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. UIRefreshControl *ref = [[UIRefreshControl alloc]init]; ref.tag = 200 ; ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"drag to refresh"]; ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7]; // ref.hidden = true; [ref addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged]; [self.webView.scrollView addSubview:ref]; self.webView.dataDetectorTypes=UIDataDetectorTypeAll; UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector( onBackClick:)]; //[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)]; // closeButton.title = @"Close"; self.navigationItem.leftBarButtonItem = closeButton; self.btnshare = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAutomatic] style:UIBarButtonItemStylePlain target:self action:@selector(onActionClick:)];//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onOpenOrderClick:)]; self.btnshare.tintColor = UIColorFromRGB(0x996633); self.btnemail =[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"mail"] imageWithRenderingMode:UIImageRenderingModeAutomatic] style:UIBarButtonItemStylePlain target:self action:@selector(onEmailClick:)];// [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Commit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCommitOrderClick:)]; self.btnemail.tintColor = UIColorFromRGB(0x996633); // self.btnSend = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Email", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSendMailClick:)]; self.btnsave = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"save"] imageWithRenderingMode:UIImageRenderingModeAutomatic] style:UIBarButtonItemStylePlain target:self action:@selector(onSaveClick:)]; self.btnsave.tintColor = UIColorFromRGB(0x996633); UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; fixedItem.width = 20.0f; NSMutableArray * items = [[NSMutableArray alloc]init]; [items addObject:self.btnshare]; [items addObject:fixedItem]; [items addObject:self.btnemail]; if(self.canSave) { [items addObject:fixedItem]; [items addObject:self.btnsave]; } self.navigationItem.rightBarButtonItems=items; self.btnshare.enabled =false; self.btnemail.enabled =false; self.btnsave.enabled =false; // self.url=@"http://192.168.1.3:8080/npd/test.pdf"; // NSURL* url = [NSURL URLWithString:self.url]; // // NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:2000]; // // // [self.webView loadRequest:request]; [self loadcontent]; } - (void)onBackClick:(UIButton *)sender { [self.navigationController popViewControllerAnimated:FALSE]; } -(void)ReloadData { // Count ++ ; // [mytabelview reloadData]; UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200]; [reF endRefreshing]; [self loadcontent]; } -(void) loadcontent { self.mum.hidden=false; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60*5]; //设置请求方式为get [request setHTTPMethod:@"GET"]; //添加用户会话id [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"]; //连接发送请求 NSHTTPURLResponse* urlResponse = nil; NSError *error = [[NSError alloc] init]; self.content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error]; self.filename = [urlResponse suggestedFilename]; dispatch_async(dispatch_get_main_queue(), ^{ self.navigationItem.title = self.save_name; UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200]; // self.content=nil; if(self.content!=nil&&self.content.length>0) { [reF removeFromSuperview]; // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = NSTemporaryDirectory(); NSString *filePath = [path stringByAppendingPathComponent:self.filename]; // NSError *error = [[NSError alloc] init]; // BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]; // NSAssert(bo,@"创建目录失败"); [self.content writeToFile:filePath atomically:YES]; self.btnshare.enabled =true; self.btnemail.enabled =true; self.btnsave.enabled =true; if(self.onLoadSuccess) self.onLoadSuccess(self.url); // int a=0; } else { [RAUtils message_alert:nil title:@"Open PDF Failed" controller:self]; // self.content = [self.url dataUsingEncoding:NSUTF8StringEncoding]; } ; // NSLog(@"%@",[[NSString alloc] initWithData:self.content encoding:NSASCIIStringEncoding]); // [self.webView loadData:self.content MIMEType:urlResponse.MIMEType textEncodingName:nil baseURL:nil]; }); }); } -(void)changeCell { UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200]; reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"]; if ([self respondsToSelector:@selector(ReloadData)]) [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1]; // DebugLog(@"refresh!!!!!!!!"); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)onActionClick:(id)sender { //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = NSTemporaryDirectory(); NSString* filename =self.filename; NSString *filePath = [path stringByAppendingPathComponent:filename]; [self openFile:filePath]; } - (IBAction)onSaveClick:(id)sender { //UIAlertControllerStyle两种类型UIAlertControllerStyleAlert类似UIAlertView //UIAlertControllerStyleActionSheet类似UIActionSheet UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Save pdf" message:nil preferredStyle:UIAlertControllerStyleAlert]; //block代码块取代了delegate [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) { textField.text = self.save_name; }]; UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) { UITextField *name = alertControl.textFields.firstObject; if(name.text.length==0) { [RAUtils message_alert:@"Cannot save without name. Save canceled." title:@"Name is missing" controller:self]; } else { self.save_name = name.text; self.btnsave.enabled =false; // NSMutableDictionary * info = if(self.onSavePDF) self.onSavePDF(self.save_name,self.filename); } }]; UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Cancel"); }]; [alertControl addAction:actionOne]; [alertControl addAction:alertthree]; //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField) [self presentViewController:alertControl animated:YES completion:nil]; } - (IBAction)onEmailClick:(id)sender { //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = NSTemporaryDirectory(); NSString* filename =self.filename; NSString *filePath = [path stringByAppendingPathComponent:filename]; MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init]; mc.mailComposeDelegate = self; [mc setSubject:self.mail_subject]; [mc setToRecipients:self.mail_to]; if(self.mail_content==nil) self.mail_content=@""; NSString* htmlbody = [NSString stringWithFormat:@"
%@
",self.mail_content]; [mc setMessageBody:htmlbody isHTML:YES]; NSData *data = [NSData dataWithContentsOfFile:filePath]; if(self.attachment_name.length>0) filename = self.attachment_name; [mc addAttachmentData:data mimeType:@"application/pdf" fileName:filename]; [self presentModalViewController:mc animated:YES]; return; } -(void)openFile: (NSString *) file_url { NSURL *file_URL = [NSURL fileURLWithPath:file_url]; if (file_URL != nil) { if (self.fileInteractionController == nil) { //_fileInteractionController = [[UIDocumentInteractionController alloc] init]; _fileInteractionController = [UIDocumentInteractionController interactionControllerWithURL:file_URL]; _fileInteractionController.delegate = self; // [_fileInteractionController retain];//不适用ARC,记得RETAIN 使用ARC注释这一行 } else { self.fileInteractionController.URL = file_URL; } // [self.fileInteractionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES]; [self.fileInteractionController setName:self.mail_subject]; // [self.fileInteractionController setAnnotation:<#(id _Nullable)#>; [self.fileInteractionController presentOptionsMenuFromBarButtonItem:self.btnshare animated:YES]; // [self.fileInteractionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES]; // [self.fileInteractionController presentPreviewAnimated:YES]; } } - (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body { NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@", to, cc, subject, body]; str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]]; } #pragma mark methods for the UIDocumentInteractionControllerDelegate - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller { // if (controller == self.fileInteractionController) { // self.fileInteractionController = nil; // } } - (void)previewDocumentWithURL:(NSURL*)url { UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url]; preview.delegate = self; [preview presentPreviewAnimated:YES]; } - (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller { } - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{ return self; } - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{ return self.view.frame; } - (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{ return self.view; } - (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(nullable NSString *)application // bundle ID { } #pragma mark - web view delegate - (void)webViewDidFinishLoad:(UIWebView *)webView { self.mum.hidden=true; } #pragma mark -MFMailComposeViewControllerDelegate delegate - (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error { switch (result) { case MFMailComposeResultCancelled: NSLog(@"Mail send canceled..."); break; case MFMailComposeResultSaved: NSLog(@"Mail saved..."); break; case MFMailComposeResultSent: NSLog(@"Mail sent..."); break; case MFMailComposeResultFailed: NSLog(@"Mail send errored: %@...", [error localizedDescription]); break; default: break; } [self dismissModalViewControllerAnimated:YES]; } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end