【问题标题】:Issue sending image using Multipeer Connectivity使用 Multipeer Connectivity 发送图像问题
【发布时间】:2016-01-17 05:07:17
【问题描述】:

我有一个使用 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 设备来测试它。

【问题讨论】:

  • 似乎使用sendData 命令有效(至少对于小图像)这对我来说很好。但是知道共享图像的资源方法出了什么问题仍然会很高兴。我将使用尝试这两种方法的代码更新复制器应用程序。

标签: ios nsfilemanager multipeer-connectivity


【解决方案1】:

我试过了,对我来说,我所要做的就是立即从本地 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)
    }
}

【讨论】:

  • 哇,我以为我已经尝试过了。很高兴知道有一个解决方案。
【解决方案2】:

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

【讨论】:

  • 它是file:///private/var/mobile/Containers/Data/Application/FE5CF814-5BD4-40A9-9444-C8776F3153DC/tmp/resource.GyAEIClpxGZEfzmy。然后我将它复制到用户的目录并添加.png 后缀:file:///var/mobile/Containers/Data/Application/FE5CF814-5BD4-40A9-9444-C8776F3153DC/Documents/temp/5535AACE-2C7D-4337-BBCF-8F62BC51239C.png。我会用这些信息更新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多