5

I have a iOS Share Extension written in Swift.

This is my first with Swift and I'm having issues with the Share Extension closing before the actions are completed. This Share Extension uploads an audio file to an API. The audio file has to be base64 before sending it to the server. It seems like it works for audio files that are smaller than 30 seconds or so but once they are larger, it seems that the share extension closes the code down and it never runs.

Below is the code:

    override func didSelectPost() {
    let defaults = NSUserDefaults(suiteName: suiteName)
    var authorization: String? = defaults!.stringForKey("Authorization")
    authorization = authorization!.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

    if let content = extensionContext!.inputItems[0] as? NSExtensionItem {
        let contentType = kUTTypeAudio as String

        if let contents = content.attachments as? [NSItemProvider] {
            for attachment in contents {
                attachment.loadItemForTypeIdentifier(contentType, options: nil) { data, error in
                    let url = data as! NSURL

                    do {

                        let audioData = try NSData(contentsOfURL: url, options: NSDataReadingOptions())
                        let base64Audio = audioData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
                        print(base64Audio)


                        let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(self.suiteNameSessionConfig)
                        // Extensions aren't allowed their own cache disk space. Need to share with application
                        sessionConfig.sharedContainerIdentifier = self.suiteName
                        let session = NSURLSession(configuration: sessionConfig)

                        let url = NSURL(string: "https://api.example.com/upload")
                        let request = NSMutableURLRequest(URL: url!)
                        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
                        request.setValue("application/json", forHTTPHeaderField: "Accept")
                        request.setValue(authorization!, forHTTPHeaderField: "Authorization")

                        request.HTTPMethod = "POST"

                        let jsonObject:[String: AnyObject] = [ "recording": [ "file": "data:audio/x-m4a;base64," + base64Audio] ]


                        var jsonError: NSError?
                        do {
                            let jsonData = try NSJSONSerialization.dataWithJSONObject(jsonObject, options:[])
                            request.HTTPBody = jsonData
                        } catch {
                            request.HTTPBody = nil
                        }


                        let task = session.dataTaskWithRequest(request)
                        task.resume()


                        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
                    } catch {
                        print(error)
                        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
                    }
                }
            }

        } else {
            self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
        }
    } else {
        self.extensionContext!.completeRequestReturningItems([], completionHandler: nil)
    }
}
iGatiTech
  • 2,306
  • 1
  • 21
  • 45
Kyle
  • 1,058
  • 2
  • 10
  • 22
  • As far as I know, there are tight restrictions on how much RAM you're allowed to consume in an extension. Perhaps experiment with compression levels and/or different audio APIs which might stream the audio without storing more than a few seconds in memory. Beware the RAM limit might be a percentage of the device's hardware RAM, so test on lower spec/older devices. – Abhi Beckert Jan 24 '18 at 06:58
  • Hello @Kyle, Have you found any solution, I am facing same issue. – Mehul Thakkar Mar 23 '18 at 11:27
  • I'm having the same issue with Share Extension in Swift running on iOS 16.0.1. My app extension is automatically killed after ~10sec. My view controller contains a tableView with 3 cell (1 cell with a textfield cells and 2 standard cell). – Thibault Sep 19 '22 at 07:13

0 Answers0