How to extract a zip file and get the extracted components in a Share Extension in Swift

[亡魂溺海] 提交于 2019-12-07 05:09:33

问题


I need to do the following-

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

  2. 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.

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.

Here is my 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)
    }

}

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

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-build-an-ios-share-extension-in-swift-4a2019935b2e

Please guide me. I use swift 3.


回答1:


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)


来源:https://stackoverflow.com/questions/45194916/how-to-extract-a-zip-file-and-get-the-extracted-components-in-a-share-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!