I've got an app that uses Multipeer Connectivity to send files between devices. On the receiving device, didFinishReceivingResourceWithNamelocalURL
is called, but the file at the localURL
seems to be empty. Code below:
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
}
I've also tried getting the NSData
at localURL
, but it ends up being nil
.
photo
is a UIImage
selected from the user's photos library. Any thoughts on what could be going wrong?
More Info:
I checked the file system on the receiving device, and the image is there. It seems something is causing the UIImage
constructor to fail with any image received over MPC.
Sample Project:
I've written a small reproducer app on GitHub. You'll need two iOS devices to test it out.
I tried this and for me all I had to do was convert to an NSData immediately from the local URL as such:
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)
}
}