美文网首页
swiftui Share Extension

swiftui Share Extension

作者: 光彩影 | 来源:发表于2024-04-22 10:28 被阅读0次

    shareAction Info

    <?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>NSExtension</key>
        <dict>
            <key>NSExtensionAttributes</key>
            <dict>
                <key>NSExtensionActivationRule</key>
                <dict>
                    <key>NSExtensionActivationSupportsText</key>
                    <false/>
                    <key>NSExtensionActivationSupportsImageWithMaxCount</key>
                    <integer>1</integer>
                </dict>
            </dict>
            <key>NSExtensionMainStoryboard</key>
            <string>MainInterface</string>
            <key>NSExtensionPointIdentifier</key>
            <string>com.apple.share-services</string>
            <key>NSExtensionSupportedAttachmentTypes</key>
            <array>
                <string>public.audio</string>
            </array>
        </dict>
    </dict>
    </plist>
    
    <!--NSExtensionActivationRule-->
    <!--            <string>TRUEPREDICATE</string>-->
    <!--            <string>SUBQUERY(extensionItems, $extensionItem, SUBQUERY($extensionItem.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.audio").@count == 1).@count == 1</string>-->
    
    

    ShareViewController

    import SwiftUI
    import Social
    import UniformTypeIdentifiers
    import UIKit
    
    
    class ShareViewController: SLComposeServiceViewController {
    
        override func isContentValid() -> Bool {
            guard let inputItems = self.extensionContext?.inputItems.map({ $0 as? NSExtensionItem }) else {
    //            self.extensionContext?.cancelRequest(withError: ShareError(message: "extensionItem error"))
                return false
            }
    
            for inputItem in inputItems {
                guard let providers = inputItem?.attachments else { return false }
    
                for itemProvider in providers {
                    if itemProvider.hasItemConformingToTypeIdentifier(UTType.image.identifier as String) {
                        itemProvider.loadDataRepresentation(forTypeIdentifier: UTType.image.identifier as String) { (data, error) in
                            if error != nil {
                                self.extensionContext?.cancelRequest(withError: error!)
                                return
                            }
    
                            guard let imgDataPath = data else {
    //                            self.extensionContext?.cancelRequest(withError: ShareError(message: "data error"))
                                return
                            }
    
                            // 分享的图片
                            let ud = UserDefaults.init(suiteName: "group.com.znp.testplay")
                            ud?.setValue(imgDataPath, forKey: "SHARE_IMAGE_KEY")
                            ud?.setValue(true, forKey: "New_SHARE_KEY")
                            self.openContainerApp()
                        }
                    }
                }
            }
    
            self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
            return true
        }
    
        override func didSelectPost() {
            // This function can be used to handle actions when the user selects the post button.
        }
    
        override func configurationItems() -> [Any]! {
            // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
            return []
        }
    
        /// 打开ContainerAPP
        private func openContainerApp() {
            let scheme = "testplay://"
            let url: URL = URL(string: scheme)!
    
            let context = NSExtensionContext()
            context.open(url, completionHandler: nil)
    
            var responder = self as UIResponder?
            let selectorOpenURL = sel_registerName("openURL:")
    
            while responder != nil {
                if responder!.responds(to: selectorOpenURL) {
                    responder!.perform(selectorOpenURL, with: url)
                    break
                }
                responder = responder?.next
            }
        }
    }
    
    

    swiftui 获取

    //
    //  ContentView.swift
    //  testplay
    //
    //  Created by 1 on 2024/4/17.
    //
    
    import SwiftUI
    struct ContentView: View {
        
        @State var imageData: Data? = nil
        
        var body: some View {
            //导航区视图控制
            NavigationView {
                //使用垂直布局
                VStack {
                    Spacer()
                    if let imageData = imageData,let uiImage = UIImage(data: imageData){
                        Image(uiImage: uiImage)
                            .resizable() // 允许图片缩放
                            .scaledToFit() // 保持图片的宽高比
                    }else {
                        Text("无法加载图片")
                    }
                    Spacer()
                }
                //导航区域的头部文本信息
                .navigationTitle("test")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.primary.opacity(0.04).ignoresSafeArea())
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                                    // 当应用程序变为活跃状态时,这里的代码会被执行
                                    print("应用程序已变为活跃状态。")
                    let ud = UserDefaults.init(suiteName: "group.com.znp.testplay")
                    if let newShare = ud?.value(forKey: "New_SHARE_KEY") as? Bool{
                        if newShare{
                            if let imageData = ud?.value(forKey: "SHARE_IMAGE_KEY"){
                                self.imageData = imageData as? Data
                            }
                        }
                        ud?.setValue(false, forKey: "New_SHARE_KEY")
                    }
                    
    //                self.imageData = ud?.value(forKey: "SHARE_IMAGE_KEY")
                    
                    
                }
            }
        }
    }
    
    #Preview {
        ContentView()
    }
    
    

    学习
    https://zhuanlan.zhihu.com/p/89222926
    https://www.cnblogs.com/junhuawang/p/8182868.html
    https://www.jianshu.com/p/67ed14b1cee1
    https://www.jianshu.com/p/125e2f79bd44
    https://juejin.cn/post/7236021829000101947?share_token=5bf398ea-f682-49d9-9c7f-16758dcc18d2
    https://www.jianshu.com/p/5b9dd21438d8

    相关文章

      网友评论

          本文标题:swiftui Share Extension

          本文链接:https://www.haomeiwen.com/subject/csibxjtx.html