2013-04-03 33 views
15

Tôi đang cố gắng gửi tệp PDF bằng cách sử dụng UIActivityViewController. Cho đến nay mọi thứ hoạt động tốt bằng cách tiếp cận khá cơ bản nhưng một vấn đề tôi có là khi tôi chọn tùy chọn gửi qua thư, tên tệp PDF là Attachment-1 thay vì Calculation.PDF là tên mà tôi cung cấp tệp.Cách gửi tệp PDF bằng UIActivityViewController

Tôi không nhớ quá nhiều thay đổi về tiêu đề, nhưng việc thiếu phần mở rộng .pdf dường như gây ra sự cố khi gửi tệp cho những người có PC của Windows và tôi muốn khắc phục điều đó.

Tôi đã có một cái nhìn tại địa chỉ: Control file name of UIImage send with UIActivityViewController

Nhưng không thể nhìn thấy một phương pháp tương đương với:

[mailComposer addAttachmentData: UIImagePNGRepresentation(viewImage) mimeType:@"" fileName:@"myImage.png"]; 

rằng sẽ làm việc với một tập tin PDF. Đây có phải là một cái gì đó mà không phải là fixable mà không cần tùy biến hoặc là có một giải pháp đơn giản cho vấn đề này?

+0

Hi bao giờ con số này ra? Có cùng một vấn đề. – Mrwolfy

+0

Điều này đã giúp tôi http://stackoverflow.com/questions/15825777/uiactivityviewcontroller-sharing-image-via-email-has-no-extension/15826633#15826633, nhưng nhược điểm là, bạn phải lưu tệp trước. –

Trả lời

46

thử này

NSData *pdfData = [NSData dataWithContentsOfFile:pdfFilePath]; 
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[@"Test", pdfData] applicationActivities:nil]; 

[self presentViewController:activityViewController animated:YES completion:nil]; 

và cũng

NSString *str = [[NSBundle mainBundle] pathForResource:@"AppDistributionGuide" ofType:@"pdf"]; 
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[@"Test", [NSURL fileURLWithPath:str]] applicationActivities:nil]; 
+1

Thao tác này, chấp nhận câu trả lời này –

+3

@ iTroyd23, tôi đã thử với đề xuất của bạn nhưng tôi không thể đặt tiêu đề của tệp đính kèm. vì vậy, bạn có thể mô tả cách đặt tiêu đề của tệp đính kèm (ví dụ: myPdf.pdf) – Vats

+0

có vẻ như nó không hoạt động trong Xcode7 + iOS9 –

6

// Trong Swift

let url = NSURL.fileURLWithPath(fileName) 

    let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil) 

    presentViewController(activityViewController, 
     animated: true, 
     completion: nil) 
+0

Không hoạt động trong ios11 – ChanWarde

-1

Có thể thử loại này ..

#define IS_IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad 

    // Validate PDF using NSData 
    - (BOOL)isValidePDF:(NSData *)pdfData { 
     BOOL isPDF = false; 
     if (pdfData.length >= 1024) { 

      int startMetaCount = 4, endMetaCount = 5; 
      // check pdf data is the NSData with embedded %PDF & %%EOF 
      NSData *startPDFData = [NSData dataWithBytes:"%PDF" length:startMetaCount]; 
      NSData *endPDFData = [NSData dataWithBytes:"%%EOF" length:endMetaCount]; 
      // startPDFData, endPDFData data are the NSData with embedded in pdfData 
      NSRange startRange = [pdfData rangeOfData:startPDFData options:0 range:NSMakeRange(0, 1024)]; 
      NSRange endRange = [pdfData rangeOfData:endPDFData options:0 range:NSMakeRange(0, pdfData.length)]; 

      if (startRange.location != NSNotFound && startRange.length == startMetaCount && endRange.location != NSNotFound && endRange.length == endMetaCount) { 
       // This assumes the checkstartPDFData doesn't have a specific range in file pdf data 
       isPDF = true; 

      } else { 
       isPDF = false; 
      } 
     } 
     return isPDF; 
    } 

    // Download PDF file in asynchronous way and validate pdf file formate. 
    - (void)downloadPDFfile:(NSString *) fileName withFileURL:(NSString *) url { 
     NSString *filePath = @""; 
     dispatch_async(dispatch_get_main_queue(),^{ 
      NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; 
      filePath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:@"/Attachments/%@",[self generateName:fileName withFiletype:@"pdf"]]]; 
      NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 
      [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
       if (error) { 
         NSLog(@"Download Error:%@",error.description); 
       } else if (data && error == nil) { 
        bool checkPdfFormat = [self isValidePDF:data]; 
        if (checkPdfFormat) { 
         //saving is done on main thread 
         dispatch_async(dispatch_get_main_queue(), ^{ 
          [data writeToFile:filePath atomically:YES]; 
          NSURL *url = [NSURL fileURLWithPath:filePath]; 
          [self triggerShare:fileName withFilepath:filePath]; 
         }); 
        } 
       } 
      }]; 
     }); 
    } 

    // Trigger default share and print functionality using UIActivityViewController 
    -(void) triggerShare:(NSString*)fileName withFilepath:(NSString*)filePath { 
      * Set this available field on the activity controller */ 
      NSMutableArray *items = [NSMutableArray array]; 

      if (filePath) { 
       [items addObject:[NSURL fileURLWithPath:filePath]]; 
      } 

      UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil]; 
      [activityViewController setValue:fileName forKey:@"subject"]; // Set the mail subject. 


      if (IS_IPAD) { 
       activityViewController.modalPresentationStyle = UIModalPresentationPopover; 
       UIPopoverPresentationController *popPC = activityViewController.popoverPresentationController; 
       popPC.sourceView = self.view; 
       CGRect sourceRext = CGRectZero; 
       sourceRext.origin = CGPointMake(self.view.frame.size.width-30, 0); // I have share button in navigation bar. ;) 
       popPC.sourceRect = sourceRext; 
       popPC.permittedArrowDirections = UIPopoverArrowDirectionUp; 
      } 


      [activityViewController setCompletionWithItemsHandler: 
      ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) { 
      }]; 
      [self presentViewController:activityViewController animated:YES completion:nil]; 
    } 

    -(NSString*) generateName:(NSString*)title withFiletype:(NSString*)type { 

     NSString *subject = [title stringByReplacingOccurrencesOfString:@" " withString:@"_"]; 
     subject = [NSString stringWithFormat:@"%@.%@",subject,type]; 
     return subject; 
    } 
6

Trên niêm yết về Swift bị phản đối ở Swift 3

let url = NSURL.fileURL(withPath: fileName) 

let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil) 

present(activityViewController, 
    animated: true, 
    completion: nil) 
1

Đối Swift 3

Bạn phải có một mảng URL với đường dẫn của file PDF mà bạn muốn gửi.

let urlArray = [pdfPath1, pdfPath2] 

Sau đó tạo một UIActivityViewController:

let activityController = UIActivityViewController(activityItems: urlArray, applicationActivities: nil) 

Nếu bạn đang sử dụng một UIBarButtonItem để làm cho hành động đó, bạn có thể thực hiện điều này để ngăn chặn một lỗi trên iPad:

if let popover = activityController.popoverPresentationController { 
    popover.barButtonItem = self.barButtonItem 
} 

Cuối cùng bạn phải trình bày số activityController:

self.present(activityController, animated: true, completion: nil) 
Các vấn đề liên quan