SORU
30 EKİM 2011, Pazar


İOS Posta uygulamasını... menü öğesi Açık destekleyen Ve Safari

Benim app "..." UIDocumentInteractionController sınıfında şey. Açık ile Safari ve Mail uygulamaları, belgeleri açmak gerekiyor Bunu nasıl başarırız?

CEVAP
5 Kasım 2011, CUMARTESİ


Bu orta derecede yetenekli bir kişi olarak başlayan bir programcı olarak, ya da şu anda bile benim için son derece sinir bozucu olduğunu biliyorum. Posta yoluyla Ç ve Safari apps/dosya... ilginç bir şekilde uygulamayı kendi içinde kuralları adlı içerir. Hadi ellerimizi kirli iPhone Güncellemelerinden bir proje. Açık Güncellemelerinden (bu eğitim için 4.2 kullanacağım) ve 'Tek kişilik' uygulama şablonu (veya boş bir proje oluştur, bir tek bir görünüm ekleyin .seçin xib).

Screenshot showing Xcode template selection sheet

Yeni oluşturulan bu uygulama, görünüm denetleyicisi (ve ilişkili xib) OfflineReaderViewController, yeniden adlandırmak ve kodu başlayabiliriz o zaman. (Ama önek ana başlık ve her dosya dokunacak.m, önünüzde her şey gerekir unutmayın!)

AppDelegate başlık girin ve içine aşağıdaki kodu yapıştırın

#import <UIKit/UIKit.h>

@class OfflineReaderViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) OfflineReaderViewController *viewController;

@end

Sonra Temsilcinin girin .m ve verbatim dosyası aşağıdaki kodu yapıştırın:

#import "AppDelegate.h"
#import "OfflineReaderViewController.h"

@implementation AppDelegate

@synthesize window;
@synthesize viewController;

-(BOOL)application:(UIApplication *)application 
           openURL:(NSURL *)url 
 sourceApplication:(NSString *)sourceApplication 
        annotation:(id)annotation 
{    
    // Make sure url indicates a file (as opposed to, e.g., http://)
    if (url != nil && [url isFileURL]) {
        // Tell our OfflineReaderViewController to process the URL
        [self.viewController handleDocumentOpenURL:url];
    }
    // Indicate that we have successfully opened the URL
    return YES;
}
- (void)dealloc
{
    [window release];
    [viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[OfflineReaderViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     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.
     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.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     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. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     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.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     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.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

@end

Bu:

-(BOOL)application:(UIApplication *)application 
               openURL:(NSURL *)url 
     sourceApplication:(NSString *)sourceApplication 
            annotation:(id)annotation 
    {    
        if (url != nil && [url isFileURL]) {
            [self.viewController handleDocumentOpenURL:url];
        }    
        return YES;
    }

Bu tek en önemli parçası oyundur. İçin, yıkın kendi ilgili bölümleri: -(BOOL)application:(UIApplication *)application bizim örnek uygulama; openURL:(NSURL *)url URL gönderilmiş söyle bize ne açık; sourceApplication:(NSString *)sourceApplication uygulama gönderilen bağlantı; annotation:(id)annotation ekstra bir özellik değil.

Şimdi, bizim xib düzen vermeliyiz. Girin xib (olmalı "başlıklı OfflineReaderViewController', ama önemli değil bir xib, sürece diyoruz initWithNibName: (vermeyeceğiz)), ve bunu gibi resmi aşağıda:

Screenshot of IB layout

UIWebView'nin özellikleri ve "Ölçekler Sayfa" bu bize izin ver, ve uzaklaştırmak için kullanılır. web sayfalarında Uygun kontrol girersen ÇOK önemlidir Bağlantıları hakkında henüz merak etme, o kısa bir süre oluşturmak olacak.

Aşağıda OfflineReaderViewController başlık ve yapıştırın girin:

#import <UIKit/UIKit.h>

@interface OfflineReaderViewController : UIViewController 
<UIDocumentInteractionControllerDelegate> {
    IBOutlet UIWebView *webView;
}

-(void)openDocumentIn;
-(void)handleDocumentOpenURL:(NSURL *)url;
-(void)displayAlert:(NSString *) str;
-(void)loadFileFromDocumentsFolder:(NSString *) filename;
-(void)listFilesFromDocumentsFolder;

- (IBAction) btnDisplayFiles;

@end

Şimdi .m:

#import "OfflineReaderViewController.h"

@implementation OfflineReaderViewController

UIDocumentInteractionController *documentController;

-(void)openDocumentIn {    
    NSString * filePath = 
    [[NSBundle mainBundle] 
     pathForResource:@"Minore" ofType:@"pdf"];    
    documentController = 
    [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
    documentController.delegate = self;
    [documentController retain];
    documentController.UTI = @"com.adobe.pdf";
    [documentController presentOpenInMenuFromRect:CGRectZero 
                                           inView:self.view 
                                         animated:YES];
}

-(void)documentInteractionController:(UIDocumentInteractionController *)controller 
       willBeginSendingToApplication:(NSString *)application {

}

-(void)documentInteractionController:(UIDocumentInteractionController *)controller 
          didEndSendingToApplication:(NSString *)application {

}

-(void)documentInteractionControllerDidDismissOpenInMenu:
(UIDocumentInteractionController *)controller {

}
-(void) displayAlert:(NSString *) str {
    UIAlertView *alert = 
    [[UIAlertView alloc] initWithTitle:@"Alert" 
                               message:str 
                              delegate:self
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [alert show];
    [alert release];    
}

- (void)handleDocumentOpenURL:(NSURL *)url {
    [self displayAlert:[url absoluteString]];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];        
    [webView setUserInteractionEnabled:YES];    
    [webView loadRequest:requestObj];
}


-(void)loadFileFromDocumentsFolder:(NSString *) filename {
    //---get the path of the Documents folder---   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(  
                                                         NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0];     
    NSString *filePath = [documentsDirectory 
                          stringByAppendingPathComponent:filename];    
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];        
    [self handleDocumentOpenURL:fileUrl];
}

-(void)listFilesFromDocumentsFolder {    
    //---get the path of the Documents folder---    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(     
                                                         NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *fileList =   
    [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
    NSMutableString *filesStr = 
    [NSMutableString stringWithString:@"Files in Documents folder \n"];
    for (NSString *s in fileList){    
        [filesStr appendFormat:@"%@ \n", s];
    }
    [self displayAlert:filesStr];    
    [self loadFileFromDocumentsFolder:@"0470918020.pdf"];
}

- (IBAction) btnDisplayFiles {
    [self listFilesFromDocumentsFolder];    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self openDocumentIn];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

O sen kimsin aktif olarak izliyor ve sadece kopyalama her şeyi anlatırım sana (şaka) biliyorum bu satır: [[NSBundle mainBundle] pathForResource:@"Minore" ofType:@"pdf"]; bizim, bir SİGABRT çünkü, şey, dosya yok! Yani, sürükle yerden çekmiş olduğunuz herhangi bir genel PDF (kim bakmıyor boş zamanlarını belgeleri büyük miktarda harcamak? çünkü here tavsiye ederim) o zaman başlığı kopyalayıp soneki ile yapıştırın (.pdf) kaldırıldı; ofType:@"pdf" bölümü bizim için o ilgilenir. O bitince bu gibi görünmelidir hattı: [[NSBundle mainBundle] pathForResource:@"//file name//" ofType:@"pdf"];

Şimdi geri xib girip IBOutlets Bu kanca! Tüm söyledim, burada "Dosya sahibi" sekmesine gibi görünmelidir: . senin ne

Screenshot showing established connections

İşimiz bitti gibi görünüyor...ama bir dakika! Her şey bir "..." menüsü ve çalışıyor! Açmak için yapmadık Eh, etrafında mucking olduğu ortaya çıktı .plist dosyası gerekli. Uygulamasını açın .(hızlı bir sağ tıklama ile, sonra ^ Açık Olarak seçin . plist Kaynak Kodu) ve aşağıdaki yapıştırın:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIconFiles</key>
    <array/>
    <key>CFBundleIdentifier</key>
    <string>CodaFi.${PRODUCT_NAME:rfc1034identifier}</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>1.0</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UIFileSharingEnabled</key>
    <true/>
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeName</key>
            <string>PDF Document</string>
            <key>LSHandlerRank</key>
            <string>Alternate</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>LSItemContentTypes</key>
            <array>
                <string>com.adobe.pdf</string>
            </array>
        </dict>
    </array>
</dict>
</plist>

[Yan not: dikkat et dalga geçiyorum kaynak kodunun herhangi bir plist, bunu bilmiyorsan ne yapıyorsun, sen-ebil almak korkunç 'Bu dosya bozuldu' hatadan Güncellemelerinden]

Eğer sağ tıklayın ve ^ Olarak Aç seçeneğini seçin bir tane olsaydı . Özellik Listesinde, bu gibi görünecektir:

Shot of Xcode plist editor window

Orada denilen ÇOK önemli bir alan var 'Uygulama iTunes dosya paylaşımını destekler'. Bunun için "EVET", ya da app dosya paylaşımı destek olarak. iTunes görünmez ayarlanmalıdır

'Tür' alan bizim örnek açabilir belge türlerini belirtir. Belge Oku rolünü bulmak ve İDRAR yolu enfeksiyonu için genişletin. Bu benzersiz tanımlayıcı (Benzersiz bir Tür Tanımlayıcılar; bu kısaltma şimdi ne demek belirgin görünüyor, değil mi?) dosya her türlü vardır. İDRAR yolu Bulucu genel belge görüntü değiştirdikleri için hangi dosya türü güzel lokalize görüntü (bana inanmıyorsan, önemsiz dosya uzantısını yeniden adlandırın .ve güzel bir resim almaya çalışın ouhbasdvluhb!) Eğer kendi özel formatı açmak isteseydim (ki Bir sağlar .sonra İYE alanında com.CodaFi.code gibi bir şey (ters hiçbir ipucu olanlar için gösterim DNS) koyardım ve Belge Türü İsim olurdu dosya kodu) 'CodaFi Belge'. Rütbe ve Rol işleyicisi bizim rütbe alternatif dosya bize ait değil çünkü) ve rolümüz olduğu için çok kolay olmalı işleyicisi görüntüleyici (çünkü biz bundan daha önemli bir şey gerekmez. Bizim örnekte olduğu gibi kalsın öyle bir görüntüleyici ve editörü.

İleride referans, İYE bir şey var resmi sistemi-ilan adlandırma düzenleri ne zaman geliyorlar gelen saygın kaynakları (Oracle, Microsoft, Apple kendisi) bulunabilir Uniform Type Identifier Reference Guide ama listelenir here pedantry aşkına.

Şimdi, kaçalım 'er! Kod hatasız, birebir ve o lanet xib bağlantıları haklısın kopyalanan varsayarak inşa etmeli. Şimdi sana ilk uygulama başlattığınızda, oyun arasından seçim yapabilirsiniz belgeyi açmak için seçeneği ile sunulmalıdır. Seçimini, kod gerçek et diğer belgeler açıyor! Safari QuickLook veya açmak için herhangi bir PDF için Safari ve arama başlatın. Sonra "Aç..." menü, bizim app geldi! Tıklayın. Değiş tokuş animasyon alacaksın ve bir uyarı dosyanın yerini bulacaktır. Bunu kapatmak için, UIWebView PDF yüklü olacak. Posta app işlevselliği ekler ile benzer vardır. Ayrıca uygulamanız için bu PDF'leri arayabilirsiniz.

İşte bu kadar, bitti. Zevk ve mutlu kodlama!

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • andyabc45

    andyabc45

    1 Mayıs 2011
  • GoogleTechTalks

    GoogleTechTa

    15 AĞUSTOS 2007
  • Phlearn Photoshop and Photography Tutorials

    Phlearn Phot

    11 EKİM 2011