我正在尝试使用 sendResourceAtURL 发送我通过imagePickerController选择的图像。 我将方法 didFinishPickingMediaWithInfo 中的网址设为
NSURL *refURL = [info objectForKey:UIImagePickerControllerReferenceURL];
但是当我打电话时
[self.mySession sendResourceAtURL:refURL withName:@"test" toPeer:peerid withCompletionHandler:^(NSError *error){
if (error)....
我总是得到不受支持的资源类型错误。 我相信网址的构造不正确,我需要其他的。 当我在我的包中创建一个包含本地文件的url时,它会被传输正常。 有什么想法吗?
谢谢, Zois
答案 0 :(得分:4)
我使用了Multipeer Group Chat示例应用程序中提供的代码并且工作正常。首先必须将文件写入文档目录,然后发送该URL。
// Don't block the UI when writing the image to documents
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// We only handle a still image
UIImage *imageToSave = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
// Save the new image to the documents directory
NSData *pngData = UIImageJPEGRepresentation(imageToSave, 1.0);
// Create a unique file name
NSDateFormatter *inFormat = [NSDateFormatter new];
[inFormat setDateFormat:@"yyMMdd-HHmmss"];
NSString *imageName = [NSString stringWithFormat:@"image-%@.JPG", [inFormat stringFromDate:[NSDate date]]];
// Create a file path to our documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
[pngData writeToFile:filePath atomically:YES]; // Write the file
// Get a URL for this file resource
NSURL *imageUrl = [NSURL fileURLWithPath:filePath];
MCPeerID *peer = self.session.connectedPeers[0];
[self.session sendResourceAtURL:imageUrl withName:imageName toPeer:peer withCompletionHandler:^(NSError *error) {
if (error) {
NSLog(@"Failed to send picture to %@, %@", peer.displayName, error.localizedDescription);
return;
}
NSLog(@"Sent picture to %@", peer.displayName);
//Clean up the temp file
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtURL:imageUrl error:nil];
}];
});