2014-10-04 18 views

Trả lời

18

Phương thức +mainBundle trả về gói chứa "tệp thi hành ứng dụng hiện tại", là thư mục con của ứng dụng của bạn khi được gọi từ trong tiện ích mở rộng.

Giải pháp này liên quan đến việc bóc hai cấp thư mục khỏi URL của gói, khi kết thúc bằng "appex".

Objective-C

NSBundle *bundle = [NSBundle mainBundle]; 
if ([[bundle.bundleURL pathExtension] isEqualToString:@"appex"]) { 
    // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex 
    bundle = [NSBundle bundleWithURL:[[bundle.bundleURL URLByDeletingLastPathComponent] URLByDeletingLastPathComponent]]; 
} 

NSString *appDisplayName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"]; 

Swift 2,2

var bundle = NSBundle.mainBundle() 
if bundle.bundleURL.pathExtension == "appex" { 
    // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex 
    bundle = NSBundle(URL: bundle.bundleURL.URLByDeletingLastPathComponent!.URLByDeletingLastPathComponent!)! 
} 

let appDisplayName = bundle.objectForInfoDictionaryKey("CFBundleDisplayName") 

Swift 3

var bundle = Bundle.main 
if bundle.bundleURL.pathExtension == "appex" { 
    // Peel off two directory levels - MY_APP.app/PlugIns/MY_APP_EXTENSION.appex 
    let url = bundle.bundleURL.deletingLastPathComponent().deletingLastPathComponent() 
    if let otherBundle = Bundle(url: url) { 
     bundle = otherBundle 
    } 
} 

let appDisplayName = bundle.object(forInfoDictionaryKey: "CFBundleDisplayName") 

này sẽ phá vỡ nếu Pathé xtension hoặc cấu trúc thư mục cho một phần mở rộng iOS bao giờ thay đổi.

+0

Cảm ơn vì điều này! Bạn đã có thể tải ứng dụng AppStore theo cách này chưa? – ewindsor

+0

Có, không có API riêng nào được sử dụng tại đây. Chúng tôi đã sử dụng tiện ích này trong tiện ích watchOS 1 của chúng tôi để tải mô hình đối tượng được quản lý cho 'UIManagedDocument' từ gói ứng dụng iOS chính. – phatblat

+0

Ah tuyệt vời. Cảm ơn vì sự thấu hiểu. – ewindsor

Các vấn đề liên quan