1.下载SDK包,然后拖入项目中
2.导入对应的库
3.在Xcode中,填写你所注册的微信应用程序id(如下图所示),此步为配置应用间的跳转
4.就说明没有针对iOS9 增加白名单。在info.plist文件中加入 LSApplicationQueriesSchemes (只写item0,item1).
#import "WXApi.h"
@interface LoginViewController ()<WXApiDelegate>
- (void)viewDidLoad {
[superviewDidLoad];
[[NSNotificationCenterdefaultCenter] addObserver:self
selector:@selector(WeiXinRegisterAndLogin)
name:@"weixin"
object:nil];
- (IBAction)weixinButtonClick:(id)sender {
if ([WXApiisWXAppInstalled]) {//判断手机上是否有微信
if ([WXApiisWXAppSupportApi]) {//判断当前的微信版本是否支持注册登录
//构造SendAuthReq结构体,
SendAuthReq *req = [[SendAuthReqalloc] init];
req.scope =@"snsapi_message,snsapi_userinfo,snsapi_friend,snsapi_contact";
req.state =@"wechat";
req.openID=weixinAppid;
[WXApisendReq:req];
}else{
UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"温馨提示"message:@"当前微信版本过低,请先升级"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionConfirm = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:nil];
[alert addAction:actionConfirm];
[selfpresentViewController:alertanimated:YEScompletion:nil];
}
}else{
[self.weixinButtonsetHidden:YES];
UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"温馨提示"message:@"请先安装微信客户端"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionConfirm = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleDefaulthandler:nil];
[alert addAction:actionConfirm];
[selfpresentViewController:alertanimated:YEScompletion:nil];
}
}
// 微信注册登录功能
- (void)WeiXinRegisterAndLogin {
//下面是我的注册登录功能,对大家无用。
AFHTTPSessionManager *manager = [AFHTTPSessionManagermanager];
manager.requestSerializer=[AFJSONRequestSerializerserializer];
[manager POST:urlparameters:parameters progress:nilsuccess:^(NSURLSessionTask *task,id responseObject) {
NSString *success=[responseObjectobjectForKey:@"status"];
if ([successisEqualToString:@"success"]) {
NSLog(@"register send success!");
NSString *userUrl;
[selfgetResponse:userUrl :delegate.nickname :delegate.nickname];
}elseif ([success isEqualToString:@"exist"]){
NSString *userUrl;
[selfgetResponse:userUrl :delegate.nickname :delegate.nickname];
}else{
NSLog(@"注册失败");
}
} failure:^(NSURLSessionTask *operation,NSError *error) {
NSLog(@"Error: %@", error);
}];
}
代码2:单例界面
#import "WXApi.h"
@interface AppDelegate :UIResponder <UIApplicationDelegate,WXApiDelegate>
@property (strong,nonatomic) NSString *access_token;
@property (strong,nonatomic) NSString *openid;
@property (strong,nonatomic) NSString *nickname;// 用户昵称
@property (strong,nonatomic) NSString *headimgurl;// 用户头像地址
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//微信注册
[WXApiregisterApp:weixinAppidwithDescription:@"wechat"];
//向微信注册支持的文件类型
UInt64 typeFlag =MMAPP_SUPPORT_TEXT | MMAPP_SUPPORT_PICTURE | MMAPP_SUPPORT_LOCATION | MMAPP_SUPPORT_VIDEO |MMAPP_SUPPORT_AUDIO |MMAPP_SUPPORT_WEBPAGE | MMAPP_SUPPORT_DOC | MMAPP_SUPPORT_DOCX |MMAPP_SUPPORT_PPT | MMAPP_SUPPORT_PPTX | MMAPP_SUPPORT_XLS |MMAPP_SUPPORT_XLSX | MMAPP_SUPPORT_PDF;
[WXApiregisterAppSupportContentFlag:typeFlag];
returnYES;
}
#pragma mark-微信重写的方法,微信确认登录后返回调用的方法
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url sourceApplication:(nullableNSString *)sourceApplication annotation:(nonnullid)annotation{
return [WXApihandleOpenURL:url delegate:self];
}
#pragma mark-WXApiDelegate
-(void)onResp:(BaseResp *)resp{
SendAuthResp *aresp = (SendAuthResp *)resp;
if (aresp.errCode ==0) { //用户同意
// 获取access_token
// 格式:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
NSString *url =[NSStringstringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",weixinAppid,weixinSecret, aresp.code];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
NSURL *zoneUrl = [NSURLURLWithString:url];
NSString *zoneStr = [NSStringstringWithContentsOfURL:zoneUrlencoding:NSUTF8StringEncodingerror:nil];
NSData *data = [zoneStrdataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];
_openid = [dicobjectForKey:@"openid"];// 初始化
_access_token = [dicobjectForKey:@"access_token"];
NSLog(@"dic = %@", dic);
[selfgetUserInfo]; //获取用户信息
}
});
});
} elseif (aresp.errCode == -2) {
NSLog(@"用户取消登录");
} elseif (aresp.errCode == -4) {
NSLog(@"用户拒绝登录");
} else {
NSLog(@"errCode = %d", aresp.errCode);
NSLog(@"code = %@", aresp.code);
}
}
// 获取用户信息
- (void)getUserInfo {
NSString *url = [NSStringstringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token,self.openid];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
NSURL *zoneUrl = [NSURLURLWithString:url];
NSString *zoneStr = [NSStringstringWithContentsOfURL:zoneUrlencoding:NSUTF8StringEncodingerror:nil];
NSData *data = [zoneStrdataUsingEncoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainerserror:nil];
NSLog(@"dic============%@",dic);
self.headimgurl = [dicobjectForKey:@"headimgurl"];// 传递头像地址
self.nickname = [dicobjectForKey:@"nickname"];// 传递昵称
[[NSNotificationCenterdefaultCenter] postNotificationName:@"weixin"object:nil];// 发送通知
}
});
});
}
如果还有不知道通知中心的请到我另一篇博客里学习下: