iOS開發- 檔案分享權限設定(利用iTunes匯入檔案, 並且顯示已有檔案)

來源:互聯網
上載者:User

標籤:style   class   blog   code   http   tar   

今天要實現一個功能, 通過iTunes匯入檔案到應用中, 並且在應用中對這個檔案進行編輯。

類似我們平時經常使用的 PDF閱讀器那樣的東西, 我們可以自己匯入我們的電子書。


源碼下載:https://github.com/colin1994/iTunesTest.git

下面具體介紹下實現過程。

先看。

圖1. 未實現功能前, iTunes



圖2. 實現功能後, iTunes


圖3. 實現功能後, 運行。



好了, 通過圖片, 我們可以看到實現的效果。

功能包括: 允許通過iTunes匯入檔案。 可以查看沙箱下所有檔案。


實現過程:1。在應用程式的Info.plist檔案中添加UIFileSharingEnabled鍵,並將索引值設定為YES。



2。具體代碼:

ViewController.h

////  ViewController.h//  iTunesTest////  Created by Colin on 14-6-8.//  Copyright (c) 2014年 icephone. All rights reserved.//#import <UIKit/UIKit.h>//step1. 匯入QuickLook庫和標頭檔#import <QuickLook/QuickLook.h>//step2. 繼承協議@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,UIDocumentInteractionControllerDelegate>{    //step3. 聲明顯示列表    IBOutlet UITableView *readTable;}//setp4. 聲明變數//UIDocumentInteractionController : 一個檔案互動控制器,提供應用程式管理與本地系統中的檔案的使用者互動的支援//dirArray : 儲存沙箱子裡面的所有檔案@property(nonatomic,retain) NSMutableArray *dirArray;@property (nonatomic, strong) UIDocumentInteractionController *docInteractionController;@end

ViewController.m

////  ViewController.m//  iTunesTest////  Created by Colin on 14-6-8.//  Copyright (c) 2014年 icephone. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize dirArray;@synthesize docInteractionController;- (void)viewDidLoad{    [super viewDidLoad];            //step5. 儲存一張圖片到裝置document檔案夾中(為了測試方便)    UIImage *image = [UIImage imageNamed:@"testPic.jpg"];    NSData *jpgData = UIImageJPEGRepresentation(image, 0.8);    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"testPic.jpg"]; //Add the file name    [jpgData writeToFile:filePath atomically:YES]; //Write the file            //step5. 儲存一份txt檔案到裝置document檔案夾中(為了測試方便)    char *saves = "Colin_csdn";    NSData *data = [[NSData alloc] initWithBytes:saves length:10];    filePath = [documentsPath stringByAppendingPathComponent:@"colin.txt"];    [data writeToFile:filePath atomically:YES];            //step6. 擷取沙箱裡所有檔案NSFileManager *fileManager = [NSFileManager defaultManager];//在這裡擷取應用程式Documents檔案夾裡的檔案及資料夾清單NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentDir = [documentPaths objectAtIndex:0];NSError *error = nil;NSArray *fileList = [[NSArray alloc] init];//fileList便是包含有該檔案夾下所有檔案的檔案名稱及檔案夾名的數組fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];self.dirArray = [[NSMutableArray alloc] init];for (NSString *file in fileList){[self.dirArray addObject:file];}//step6. 重新整理列表, 顯示資料[readTable reloadData];}//step7. 利用url路徑開啟UIDocumentInteractionController- (void)setupDocumentControllerWithURL:(NSURL *)url{    if (self.docInteractionController == nil)    {        self.docInteractionController = [UIDocumentInteractionController interactionControllerWithURL:url];        self.docInteractionController.delegate = self;    }    else    {        self.docInteractionController.URL = url;    }}#pragma mark- 列表操作- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{return 1;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{static NSString *CellName = @"CellName";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellName];if (cell == nil){cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellName];cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;}NSURL *fileURL= nil;NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentDir = [documentPaths objectAtIndex:0];NSString *path = [documentDir stringByAppendingPathComponent:[self.dirArray objectAtIndex:indexPath.row]];fileURL = [NSURL fileURLWithPath:path];[self setupDocumentControllerWithURL:fileURL];cell.textLabel.text = [self.dirArray objectAtIndex:indexPath.row];NSInteger iconCount = [self.docInteractionController.icons count];    if (iconCount > 0)    {        cell.imageView.image = [self.docInteractionController.icons objectAtIndex:iconCount - 1];    }    return cell;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{return [self.dirArray count];}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{QLPreviewController *previewController = [[QLPreviewController alloc] init];    previewController.dataSource = self;    previewController.delegate = self;        // start previewing the document at the current section index    previewController.currentPreviewItemIndex = indexPath.row;    [[self navigationController] pushViewController:previewController animated:YES];    //[self presentViewController:previewController animated:YES completion:nil];}#pragma mark - UIDocumentInteractionControllerDelegate- (NSString *)applicationDocumentsDirectory{return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];}- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController{    return self;}#pragma mark - QLPreviewControllerDataSource// Returns the number of items that the preview controller should preview- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{return 1;}- (void)previewControllerDidDismiss:(QLPreviewController *)controller{    // if the preview dismissed (done button touched), use this method to post-process previews}// returns the item that the preview controller should preview- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx{    NSURL *fileURL = nil;    NSIndexPath *selectedIndexPath = [readTable indexPathForSelectedRow];NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentDir = [documentPaths objectAtIndex:0];NSString *path = [documentDir stringByAppendingPathComponent:[self.dirArray objectAtIndex:selectedIndexPath.row]];fileURL = [NSURL fileURLWithPath:path];    return fileURL;}- (void)didReceiveMemoryWarning{    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.