如何在Swift的Share

如何在Swift的Share

本文介绍了如何在Swift的Share Extension中提取一个zip文件并获取提取的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下操作-

  1. 我还有另一个应用程序,其中我将以zip格式导出用户的config(.txt)和contact(.vcf).

  1. I have another app in which i will export the users config(.txt) and contacts(.vcf) in a zip format.

在第二个应用程序中,我有一个共享扩展名以获取导出的zip,在共享扩展名中,我需要提取zip文件并获取txt和vcf文件,然后将它们上传到解析服务器.

In the second app i have a share extension to get the exported zip and in the share extension, i need to extract the zip file and get both the txt and vcf files and then upload them to a parse server.

在共享扩展名中打开导出的zip之前,我已经做完了.但我无法提取压缩文件.我无法在互联网上找到答案.

I have done till opening the exported zip in the share extension. but i could not get the zip extracted.I couldn't get the answer in internet.

这是我的ShareViewController

import UIKit
import Social
import Parse
import MobileCoreServices
import SSZipArchive

class ShareViewController: SLComposeServiceViewController {

    var requird_data : NSData!
    var path : URL!

    override func viewDidLoad() {
        super.viewDidLoad()
        //Parse.setApplicationId("cGFyc2UtYXBwLXdob3N1cA==", clientKey: "")
        initUI()
        getURL()
        textView.delegate = self
        textView.keyboardType = .numberPad
    }

//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(true)
//
//    }

    func initUI()
    {

        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        title = "upup"

        navigationController?.navigationBar.tintColor = .white
        navigationController?.navigationBar.backgroundColor = UIColor(red:0.97, green:0.44, blue:0.12, alpha:1.00)
        placeholder = "Please enter your Phone number"
    }

    private func getURL() {
        let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
        let itemProvider = extensionItem.attachments?.first as! NSItemProvider
        let zip_type = String(kUTTypeZipArchive)
        if itemProvider.hasItemConformingToTypeIdentifier(zip_type) {
            itemProvider.loadItem(forTypeIdentifier: zip_type, options: nil, completionHandler: { (item, error) -> Void in
                guard let url = item as? NSURL else { return }
                print("\(item.debugDescription)")
                OperationQueue.main.addOperation {
                    self.path = url as URL
                    SSZipArchive.unzipFile(atPath: url.path!, toDestination: url.path!)
                }
            })
        } else {
            print("error")
        }
    }

    override func isContentValid() -> Bool {
        // Do validation of contentText and/or NSExtensionContext attachments here
        return true
    }

    override func didSelectPost() {
        // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

        // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    override func configurationItems() -> [Any]! {
        // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
        return []
    }

    override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
    {
        let length = ((textView.text)?.characters.count)! + text.characters.count - range.length
        let allowedset : CharacterSet = CharacterSet(charactersIn: "0123456789+").inverted as CharacterSet
        let filtered  = (text.components(separatedBy: allowedset)).joined(separator: "")

        return (length<17) && (text == filtered)
    }

}

我使用SSZipAchive提取文件.链接: https://github.com/ZipArchive/ZipArchive

I use SSZipAchive to extract the file. Link : https://github.com/ZipArchive/ZipArchive

我在Xcode 9 beta 1中运行了该应用程序.我使用了模拟器中新的Files应用程序来共享zip.以下是我的共享扩展信息Plist

I ran the application in the Xcode 9 beta 1. I used the new Files app from simulator to share the zip.Below is my Share Extensions Info.Plist

我是分享扩展程序的新手,所以我对此不太了解.上面的所有代码都是来自以下教程的点点滴滴和一些谷歌搜索.

I am newbie to share extension so i don't know much about it. All the code above are from bits and pieces from the following tutorials and a little googling.

1. https://www.appcoda.com/ios8-share-extension -swift/

2. https://hackernoon. com/how-to-to-build-an-ios-share-extension-in-swift-4a2019935b2e

请指导我.我用的是swift 3.

Please guide me.I use swift 3.

推荐答案

我找到了解决方案.为提取的项目提供目标文件路径与源文件路径相同是我的错误.将其更改为应用程序的文档目录后,我开始运行它.

I found out the solution. It was my mistake to give the destination file path for the extracted items to be the same as the source files path. After changing it to the app's documents directory i got it working.

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
SSZipArchive.unzipFile(atPath: url.path!, toDestination: documentsPath)

这篇关于如何在Swift的Share Extension中提取一个zip文件并获取提取的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 14:16