10

我创建了一个 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
}

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

共享容器

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

应用程序组和网络

4

2 回答 2

7

执行后台上传

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

let sc_uploadURL = "http://requestb.in/oha28noh"

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

设置一个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)

上述代码段需要注意的重要部分是在会话配置上设置 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)

这会调用一个构造 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
}

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

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
}

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

// Create the task, and kick it off
let task = session.dataTaskWithRequest(request!)
task.resume()

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

在此处输入图像描述

于 2018-10-18T15:21:10.403 回答
1

应用组标识符必须以“组”开头。并且必须在任何使用它的地方匹配 - 在权利文件中、在您的代码中以及在 Apple Dev 门户中。

在您的应用程序和共享扩展权利定义中,您有 $(TeamIdentifierPrefix).group.CreateDaily。这是无效的,因为它不以“group.”开头。

在您的代码中,您只有“group.CreateDaily”。如果它与您的授权文件中的内容相匹配,那就没问题了,尽管 Apple 建议使用反向域名表示法来避免冲突。

我的建议是转到证书、标识符和配置文件/标识符/AppGroups 下的Apple Dev 门户并定义您的应用程序组。苹果不会让你输入不以“group.”开头的东西。设置完成后,请确保您的权利文件和代码 (config.sharedContainerIdentifier) 中的内容匹配,然后一切正常。

于 2018-10-17T18:07:57.607 回答