[摘要]本文介绍IOS 如何将图片和文字同时分享到微信,并提供详细的示例代码供参考。
微信开放平台上的例子只有单独分享一张图片或者是单独分享一段文字。最近要做这个功能,就搜索了一下是否有这方面的文章。可能博主搜索能力有限,没找到。最后只好查阅资料,编写了这部分代码,拿出来分享一下:
WXMediaMessage *message = [WXMediaMessage message];
message.title = [NSString stringWithFormat:@"%@",self.saiarray2.title];
message.description = [NSString stringWithFormat:@"%@",self.saiarray2.content];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.saiarray2.head_img]];
//这步很关键,图片必须要压缩
NSData *data1 = UIImagePNGRepresentation([self imageWithImageSimple:[[UIImage alloc]initWithData:[[NSData alloc] initWithContentsOfURL:url]] scaledToSize:CGSizeMake(80, 80)]);
[message setThumbData:data1];
WXWebpageObject *ext = [WXWebpageObject object];
ext.webpageUrl = [NSString stringWithFormat:@"http://gift.smgtech.net/web.php?mod=index&code=index&id=%@",self.shaid];
message.mediaObject = ext;
SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
req.bText = NO;
req.message = message;
req.scene = _scene;
[WXApi sendReq:req];
图片必须按照微信SDK说明压缩到15K以内大小。压缩函数如下:
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
UIGraphicsBeginImageContext(newSize);
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}