带共享扩展的后台上传

Bes*_*esi 9 macos nsurlsession swift share-extension macos-mojave

我创建了一个macOS ShareExtension,我想用它来上传图片.

我还在测试这个,所以任何请求都会发送到https://beeceptor.com.

共享扩展工作正常,一旦我运行它就显示在预览中:

分享延期

我添加一些文字并点击"发布"

创建帖子

但是图像没有上传.这是启动后台上传的代码:

let sc_uploadURL = "https://xyz.free.beeceptor.com/api/posts" // https://beeceptor.com/console/xyz

override func didSelectPost() {
    // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
    let configName = "com.shinobicontrols.ShareAlike.BackgroundSessionConfig"
    let sessionConfig = URLSessionConfiguration.background(withIdentifier: configName)
    // Extensions aren't allowed their own cache disk space. Need to share with application
    sessionConfig.sharedContainerIdentifier = "group.CreateDaily"
    let session = URLSession(configuration: sessionConfig)

    // Prepare the URL Request
    let request = urlRequestWithImage(image: attachedImage, text: contentText)

    // Create the task, and kick it off
    let task = session.dataTask(with: request! as URLRequest)
    task.resume()

    // 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.
    extensionContext?.completeRequest(returningItems: [AnyObject](), completionHandler: nil)
}

private func urlRequestWithImage(image: NSImage?, text: String) -> NSURLRequest? {
    let url = URL(string: sc_uploadURL)!
    let request: NSMutableURLRequest? =  NSMutableURLRequest(url: url as URL)
    request?.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request?.addValue("application/json", forHTTPHeaderField: "Accept")
    request?.httpMethod = "POST"

    let jsonObject = NSMutableDictionary()
    jsonObject["text"] = text
    if let image = image {
        jsonObject["image_details"] = extractDetailsFromImage(image: image)
    }

    // Create the JSON payload
    let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: JSONSerialization.WritingOptions.prettyPrinted)
    request?.httpBody = jsonData
    return request
}
Run Code Online (Sandbox Code Playgroud)

请注意,sharedContainerIdentifier它存在于应用程序的权利以及共享扩展权利中.

共享容器

ShareExtensions位于相应的应用程序组中,并启用了传出连接.

应用程序组和网络

Kou*_*sic 7

执行后台上传

一旦用户完成了他们的输入,并点击了 Post 按钮,那么扩展应该将内容上传到某个 Web 服务的某个地方。出于本示例的目的,端点的 URL 包含在视图控制器的属性中:

let sc_uploadURL = "http://requestb.in/oha28noh"
Run Code Online (Sandbox Code Playgroud)

这是 Request Bin 服务的 URL,它为您提供一个临时 URL 以允许您测试网络操作。上面的 URL(以及示例代码中的 URL)对您不起作用,但是如果您访问 requestb.in,那么您可以获得自己的 URL 进行测试。

如前所述,扩展对有限的系统资源几乎没有压力是很重要的。因此,在点击 Post 按钮时,没有时间执行同步的前台网络操作。幸运的是,NSURLSession它提供了一个用于创建后台网络操作的简单 API,而这正是您在这里所需要的。

当用户点击 post 时调用的方法是didSelectPost(),它最简单的形式必须是这样的:

override func didSelectPost() {
  // Perform upload
  ...

  // Inform the host that we're done, so it un-blocks its UI.
  extensionContext?.completeRequestReturningItems(nil, completionHandler: nil)
}
Run Code Online (Sandbox Code Playgroud)

设置一个NSURLSession非常标准:

let configName = "com.shinobicontrols.ShareAlike.BackgroundSessionConfig"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configName)
// Extensions aren't allowed their own cache disk space. Need to share with application
sessionConfig.sharedContainerIdentifier = "group.ShareAlike"
let session = NSURLSession(configuration: sessionConfig)
Run Code Online (Sandbox Code Playgroud)

上述代码段需要注意的重要部分是在会话配置上设置 sharedContainerIdentifier 的行。这指定了 NSURLSession 可以用作缓存的容器的名称(因为扩展没有自己的可写磁盘访问权限)。这个容器需要作为宿主应用程序的一部分进行设置(即本演示中的 ShareAlike),并且可以通过 Xcode 完成:

  1. 转到应用程序目标的功能选项卡
  2. 启用应用程序组
  3. 创建一个新的应用程序组,命名为适当的东西。它必须以 group 开头。在演示中,该组称为 group.ShareAlike
  4. 让 Xcode 为您完成创建此组的过程。

在此处输入图片说明

然后您需要转到扩展的目标,并遵循相同的过程。请注意,您不需要创建新的应用程序组,而是选择您为主机应用程序创建的应用程序组。

在此处输入图片说明

这些应用程序组根据您的开发人员 ID 进行注册,签名过程确保只有您的应用程序能够访问这些共享容器。

Xcode 将为您的每个项目创建一个权利文件,其中将包含它有权访问的共享容器的名称。

现在您已经正确设置了会话,您需要创建一个 URL 请求来执行:

// Prepare the URL Request
let request = urlRequestWithImage(attachedImage, text: contentText)
Run Code Online (Sandbox Code Playgroud)

这将调用一个构造 URL 请求的方法,该请求使用 HTTP POST 发送一些 JSON,其中包括字符串内容和有关图像的一些元数据属性:

func urlRequestWithImage(image: UIImage?, text: String) -> NSURLRequest? {
  let url = NSURL.URLWithString(sc_uploadURL)
  let request = NSMutableURLRequest(URL: url)
  request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  request.addValue("application/json", forHTTPHeaderField: "Accept")
  request.HTTPMethod = "POST"

  var jsonObject = NSMutableDictionary()
  jsonObject["text"] = text
  if let image = image {
    jsonObject["image_details"] = extractDetailsFromImage(image)
  }

  // Create the JSON payload
  var jsonError: NSError?
  let jsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: nil, error: &jsonError)
  if jsonData {
    request.HTTPBody = jsonData
  } else {
    if let error = jsonError {
      println("JSON Error: \(error.localizedDescription)")
    }
  }

  return request
}
Run Code Online (Sandbox Code Playgroud)

这种方法实际上并没有创建一个上传图像的请求,尽管它可以适应这样做。相反,它使用以下方法提取有关图像的一些详细信息:

func extractDetailsFromImage(image: UIImage) -> NSDictionary {
  var resultDict = [String : AnyObject]()
  resultDict["height"] = image.size.height
  resultDict["width"] = image.size.width
  resultDict["orientation"] = image.imageOrientation.toRaw()
  resultDict["scale"] = image.scale
  resultDict["description"] = image.description
  return resultDict
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以要求会话创建与您构建的请求相关联的任务,然后对其调用 resume() 以在后台启动它:

// Create the task, and kick it off
let task = session.dataTaskWithRequest(request!)
task.resume()
Run Code Online (Sandbox Code Playgroud)

如果您现在运行此过程,并使用您自己的 requestb.in URL,那么您可以期望看到如下结果:

在此处输入图片说明