使用Multipeer Connectivity发送图像

时间:2016-01-17 05:07:17

标签: ios nsfilemanager 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
}

我还尝试在NSData获取localURL,但结果是nil

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

更多信息:

我检查了接收设备上的文件系统,图像就在那里。似乎有些事情导致UIImage构造函数失败并且通过MPC接收到任何图像。

示例项目:

我在GitHub上写了一个小reproducer app。您需要两台iOS设备才能对其进行测试。

2 个答案:

答案 0 :(得分:1)

我试过这个,对我来说,我所要做的就是立即从本地网址转换为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)
    }
}

答案 1 :(得分:0)

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

相关问题