使用 Multipeer Connectivity 发送图像

Issue sending image using Multipeer Connectivity

我有一个应用程序使用 Multipeer Connectivity 在设备之间发送文件。在接收设备上,调用了 didFinishReceivingResourceWithNamelocalURL,但 localURL 处的文件似乎是空的。代码如下:

func sendPhoto() {
    guard let imageData = UIImagePNGRepresentation(photo) else { return }
    imageData.writeToURL(photoURL, atomically: true)
    // photoURL: "/var/mobile/Containers/Data/Application/0A2C6681-FA7C-4821-8C21-E9C3768E84EC/Documents/temp/A9081EE5-5D43-499D-8DC0-D36FEC041FE0.png"

    session.sendResourceAtURL(photoURL, withName: "image.png", toPeer: otherPeer) { 
        error in
            print(error)
    }
}

func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String,
    fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
        print(error) // error is nil
        do {
            try NSFileManager.defaultManager().moveItemAtURL(localURL, toURL: profilePhotoURL)
            // profilePhotoURL: file:///var/mobile/Containers/Data/Application/FE5CF814-5BD4-40A9-9444-C8776F3153DC/Documents/temp/5535AACE-2C7D-4337-BBCF-8F62BC51239C.png
        } catch { print(error) }

        let image = UIImage(contentsOfFile: profilePhotoURL.absoluteString) // image is nil
}

我也试过在 localURL 获得 NSData,但结果是 nil

photo 是从用户的照片库中选择的 UIImage。对可能出现的问题有什么想法吗?

更多信息:

我检查了接收设备上的文件系统,图像在那里。似乎有什么原因导致 UIImage 构造函数在通过 MPC 接收任何图像时失败。

示例项目:

我在 GitHub 上写了一个小 reproducer app。您需要两个 iOS 设备来测试它。

localURL 打印成什么?我的直接怀疑是您需要一个以 file:// 为前缀的 URL 字符串才能从磁盘读取...这也可以解释为什么 URL 中的数据也为零。

我试过了,对我来说,我所要做的就是立即从本地 URL 转换为 NSData,如下所示:

func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String,
fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?) {
    var image: UIImage? = nil
    if let localData = NSData(contentsOfURL: localURL) {
        image = UIImage(data: localData)
    }
}