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)
}
}