Getting started with iOS development from samples (3)-Document Browsing

Source: Internet
Author: User
Tags call back

IOS provides browsing functions for various documents (PDF, PPT, word, txt, JPG, etc.). This is very useful because we will inevitably need to browse various documents in the app. The official sample code docinteraction shows how to browse documents in various formats on IOS.

This sample is very simple. In tableview, the list of documents under the predefined and specified directories is listed. When you click a document, you can switch to view and preview the document content:

The key points learned from this sample are:

  • Load the file list from the file directory
  • Monitors file changes in the document directory and provides real-time feedback on the UI.
  • Preview various documents

Load the file list from the file directory

IOS provides nsfilemanager to access the file system. The following code shows you how to query all files in a directory path through nsfilemanager:

- (void)directoryDidChange:(DirectoryWatcher *)folderWatcher{[self.documentURLs removeAllObjects];    // clear out the old docs and start overNSString *documentsDirectoryPath = [self applicationDocumentsDirectory];NSArray *documentsDirectoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:NULL];    for (NSString* curFileName in [documentsDirectoryContents objectEnumerator]){NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:curFileName];NSURL *fileURL = [NSURL fileURLWithPath:filePath];BOOL isDirectory;        [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];        // proceed to add the document URL to our list (ignore the "Inbox" folder)        if (!(isDirectory && [curFileName isEqualToString: @"Inbox"]))        {            [self.documentURLs addObject:fileURL];        }}[self.tableView reloadData];}

To display the file list on the UI, you can use the datasource of tableview. This section has been analyzed in the previous section. reloaddata is required.

Monitors file changes in the document directory and provides real-time feedback on the UI.

This example uses the system kernel function to monitor the file directory. first look at the Code:

- (BOOL)startMonitoringDirectory:(NSString *)dirPath{// Double initializing is not going to work...if ((dirKQRef == NULL) && (dirFD == -1) && (kq == -1)){// Open the directory we're going to watchdirFD = open([dirPath fileSystemRepresentation], O_EVTONLY);if (dirFD >= 0){// Create a kqueue for our event messages...kq = kqueue();if (kq >= 0){struct kevent eventToAdd;eventToAdd.ident  = dirFD;eventToAdd.filter = EVFILT_VNODE;eventToAdd.flags  = EV_ADD | EV_CLEAR;eventToAdd.fflags = NOTE_WRITE;eventToAdd.data   = 0;eventToAdd.udata  = NULL;int errNum = kevent(kq, &eventToAdd, 1, NULL, 0, NULL);if (errNum == 0){CFFileDescriptorContext context = { 0, self, NULL, NULL, NULL };CFRunLoopSourceRef      rls;// Passing true in the third argument so CFFileDescriptorInvalidate will close kq.dirKQRef = CFFileDescriptorCreate(NULL, kq, true, KQCallback, &context);if (dirKQRef != NULL){rls = CFFileDescriptorCreateRunLoopSource(NULL, dirKQRef, 0);if (rls != NULL){CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);CFRelease(rls);CFFileDescriptorEnableCallBacks(dirKQRef, kCFFileDescriptorReadCallBack);// If everything worked, return early and bypass shutting things downreturn YES;}// Couldn't create a runloop source, invalidate and release the CFFileDescriptorRefCFFileDescriptorInvalidate(dirKQRef);                        CFRelease(dirKQRef);dirKQRef = NULL;}}// kq is active, but something failed, close the handle...close(kq);kq = -1;}// file handle is open, but something failed, close the handle...close(dirFD);dirFD = -1;}}return NO;}

This code is basically used for kernel C functions. Although it is obscure, the process is still very simple. First, it monitors system events, then, based on the IOS thread framework, call back the callback after the file directory changes. The specific content of the callback is implemented in kqcallback. This method is also very simple, in fact, it is based on the delegate mode to call the directorydidchange method in the previous section, and then refresh the tableview content. The usage of the specific c function is not mentioned here, but it is worth learning how to call the underlying BSD system API at the IOS level.

Preview various documents

In this example, the most important point is the simplest. IOS provides qlpreviewcontroller, which allows you to directly preview the views of various documents. You only need to add the views to navigationcontroller, the Code is as follows:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    NSURL *fileURL;    if (indexPath.section == 0)    {        fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:documents[indexPath.row] ofType:nil]];    }    else    {        fileURL = [self.documentURLs objectAtIndex:indexPath.row];    }    [self setupDocumentControllerWithURL:fileURL];    [self.docInteractionController presentPreviewAnimated:YES];        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];    [previewController release];}

You can set the content and behavior of the preview in qlpreviewcontrollerdelegate and qlpreviewcontrollerdatasource. Therefore, you only need to implement qlpreviewcontrollerdelegate and qlpreviewcontrollerdatasource In the controller:

// Returns the number of items that the preview controller should preview- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{    NSInteger numToPreview = 0;        NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];    if (selectedIndexPath.section == 0)        numToPreview = NUM_DOCS;    else        numToPreview = self.documentURLs.count;        return numToPreview;}// returns the item that the preview controller should preview- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)idx{    NSURL *fileURL = nil;        NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];    if (selectedIndexPath.section == 0)    {        fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:documents[idx] ofType:nil]];    }    else    {        fileURL = [self.documentURLs objectAtIndex:idx];    }        return fileURL;}

The first method is to set the number of views for a group of documents, which will affect the previous or next page in document preview. The second method is to specify the file path for document preview, it can be seen that previewing a variety of documents in IOS is very simple, and the format of previewing is very wide, as long as the MAC preview can be supported, it can be supported here, after a simple test, we found that all common documents are supported.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.