//
// AppDelegate.m
// LocalNotification
//
// Created by Kenshin Cui on 14/03/28.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import "AppDelegate.h"
#import "KCMainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
#pragma mark - 应用代理方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
//设置全局导航条风格和颜色
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController=[[KCMainViewController alloc]init];
_window.rootViewController=mainController;
[_window makeKeyAndVisible];
//如果已经获得发送通知的授权则创建本地通知,否则请求授权(注意:如果不请求授权在设置中是没有对应的通知设置项的,也就是说如果从来没有发送过请求,即使通过设置也打不开消息允许设置)
if ([[UIApplication sharedApplication]currentUserNotificationSettings].types!=UIUserNotificationTypeNone) {
[self addLocalNotification];
}else{
[[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
return YES;
}
#pragma mark 调用过用户注册通知方法之后执行(也就是调用完registerUserNotificationSettings:方法之后执行)
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
if (notificationSettings.types!=UIUserNotificationTypeNone) {
[self addLocalNotification];
}
}
#pragma mark 进入前台后设置消息信息
-(void)applicationWillEnterForeground:(UIApplication *)application{
[[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//进入前台取消应用消息图标
}
#pragma mark - 私有方法
#pragma mark 添加本地通知
-(void)addLocalNotification{
//定义本地通知对象
UILocalNotification *notification=[[UILocalNotification alloc]init];
//设置调用时间
notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10.0];//通知触发的时间,10s以后
notification.repeatInterval=2;//通知重复次数
//notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历,使用前最好设置时区等信息以便能够自动同步时间
//设置通知属性
notification.alertBody=@"最近添加了诸多有趣的特性,是否立即体验?"; //通知主体
notification.applicationIconBadgeNumber=1;//应用程序图标右上角显示的消息数
notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片,这里使用程序启动图片
//notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音,默认消息声音
notification.soundName=@"msg.caf";//通知声音(需要真机才能听到声音)
//设置用户信息
notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息
//调用通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
#pragma mark 移除本地通知,在不需要此通知时记得移除
-(void)removeNotification{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
@end
//
// AppDelegate.m
// LocalNotification
//
// Created by Kenshin Cui on 14/03/28.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import "AppDelegate.h"
#import "KCMainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
#pragma mark - 应用代理方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
//设置全局导航条风格和颜色
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController=[[KCMainViewController alloc]init];
_window.rootViewController=mainController;
[_window makeKeyAndVisible];
//添加通知
[self addLocalNotification];
//接收通知参数
UILocalNotification *notification=[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
NSDictionary *userInfo= notification.userInfo;
[userInfo writeToFile:@"/Users/kenshincui/Desktop/didFinishLaunchingWithOptions.txt" atomically:YES];
NSLog(@"didFinishLaunchingWithOptions:The userInfo is %@.",userInfo);
return YES;
}
#pragma mark 接收本地通知时触发
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
NSDictionary *userInfo=notification.userInfo;
[userInfo writeToFile:@"/Users/kenshincui/Desktop/didReceiveLocalNotification.txt" atomically:YES];
NSLog(@"didReceiveLocalNotification:The userInfo is %@",userInfo);
}
#pragma mark 调用过用户注册通知方法之后执行(也就是调用完registerUserNotificationSettings:方法之后执行)
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
if (notificationSettings.types!=UIUserNotificationTypeNone) {
[self addLocalNotification];
}
}
#pragma mark 进入前台后设置消息信息
-(void)applicationWillEnterForeground:(UIApplication *)application{
[[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//进入前台取消应用消息图标
}
#pragma mark - 私有方法
#pragma mark 添加本地通知
-(void)addLocalNotification{
//定义本地通知对象
UILocalNotification *notification=[[UILocalNotification alloc]init];
//设置调用时间
notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10.0];//通知触发的时间,10s以后
notification.repeatInterval=2;//通知重复次数
//notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历,使用前最好设置时区等信息以便能够自动同步时间
//设置通知属性
notification.alertBody=@"最近添加了诸多有趣的特性,是否立即体验?"; //通知主体
notification.applicationIconBadgeNumber=1;//应用程序图标右上角显示的消息数
notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片
//notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音,默认消息声音
notification.soundName=@"msg.caf";//通知声音(需要真机)
//设置用户信息
notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//绑定到通知上的其他额外信息
//调用通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
@end
//
// AppDelegate.m
// pushnotification
//
// Created by Kenshin Cui on 14/03/27.
// Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//
#import "AppDelegate.h"
#import "KCMainViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
#pragma mark - 应用程序代理方法
#pragma mark 应用程序启动之后
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
_window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
_window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1];
//设置全局导航条风格和颜色
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]];
[[UINavigationBar appearance] setBarStyle:UIBarStyleBlack];
KCMainViewController *mainController=[[KCMainViewController alloc]init];
_window.rootViewController=mainController;
[_window makeKeyAndVisible];
//注册推送通知(注意iOS8注册方法发生了变化)
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
[application registerForRemoteNotifications];
return YES;
}
#pragma mark 注册推送通知之后
//在此接收设备令牌
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
[self addDeviceToken:deviceToken];
NSLog(@"device token:%@",deviceToken);
}
#pragma mark 获取device token失败后
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error.localizedDescription);
[self addDeviceToken:nil];
}
#pragma mark 接收到推送通知之后
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
NSLog(@"receiveRemoteNotification,userInfo is %@",userInfo);
}
#pragma mark - 私有方法
/**
* 添加设备令牌到服务器端
*
* @param deviceToken 设备令牌
*/
-(void)addDeviceToken:(NSData *)deviceToken{
NSString *key=@"DeviceToken";
NSData *oldToken= [[NSUserDefaults standardUserDefaults]objectForKey:key];
//如果偏好设置中的已存储设备令牌和新获取的令牌不同则存储新令牌并且发送给服务器端
if (![oldToken isEqualToData:deviceToken]) {
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:key];
[self sendDeviceTokenWidthOldDeviceToken:oldToken newDeviceToken:deviceToken];
}
}
-(void)sendDeviceTokenWidthOldDeviceToken:(NSData *)oldToken newDeviceToken:(NSData *)newToken{
//注意一定确保真机可以正常访问下面的地址
NSString *urlStr=@"http://192.168.1.101/RegisterDeviceToken.aspx";
urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];
NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10.0];
[requestM setHTTPMethod:@"POST"];
NSString *bodyStr=[NSString stringWithFormat:@"oldToken=%@&newToken=%@",oldToken,newToken];
NSData *body=[bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[requestM setHTTPBody:body];
NSURLSession *session=[NSURLSession sharedSession];
NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:requestM completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Send failure,error is :%@",error.localizedDescription);
}else{
NSLog(@"Send Success!");
}
}];
[dataTask resume];
}
@end
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMJ.Framework.Data;
namespace WebServer
{
public partial class RegisterDeviceToken : System.Web.UI.Page
{
private string _appID = @"com.cmjstudio.pushnotification";
private SqlHelper _helper = new SqlHelper();
protected void Page_Load(object sender, EventArgs e)
{
try
{
string oldToken = Request["oldToken"] + "";
string newToken = Request["newToken"] + "";
string sql = "";
//如果传递旧的设备令牌则删除旧令牌添加新令牌
if (oldToken != "")
{
sql = string.Format("DELETE FROM dbo.Device WHERE AppID='{0}' AND DeviceToken='{1}';", _appID, oldToken);
}
sql += string.Format(@"IF NOT EXISTS (SELECT ID FROM dbo.Device WHERE AppID='{0}' AND DeviceToken='{1}')
INSERT INTO dbo.Device ( AppID, DeviceToken ) VALUES ( N'{0}', N'{1}');", _appID, newToken);
_helper.ExecuteNonQuery(sql);
Response.Write("注册成功!");
}
catch(Exception ex)
{
Response.Write("注册失败,错误详情:"+ex.ToString());
}
}
}
}
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PushSharp;
using PushSharp.Apple;
using CMJ.Framework.Data;
using CMJ.Framework.Logging;
using CMJ.Framework.Windows.Forms;
namespace PushNotificationServer
{
public partial class frmMain : PersonalizeForm
{
private string _appID = @"com.cmjstudio.pushnotification";
private SqlHelper _helper = new SqlHelper();
public frmMain()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnSend_Click(object sender, EventArgs e)
{
List<string> deviceTokens = GetDeviceToken();
SendMessage(deviceTokens, tbMessage.Text);
}
#region 发送消息
/// <summary>
/// 取得所有设备令牌
/// </summary>
/// <returns>设备令牌</returns>
private List<string> GetDeviceToken()
{
List<string> deviceTokens = new List<string>();
string sql = string.Format("SELECT DeviceToken FROM dbo.Device WHERE AppID='{0}'",_appID);
DataTable dt = _helper.GetDataTable(sql);
if(dt.Rows.Count>0)
{
foreach(DataRow dr in dt.Rows)
{
deviceTokens.Add((dr["DeviceToken"]+"").TrimStart('<').TrimEnd('>').Replace(" ",""));
}
}
return deviceTokens;
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="deviceToken">设备令牌</param>
/// <param name="message">消息内容</param>
private void SendMessage(List<string> deviceToken, string message)
{
//创建推送对象
var pusher = new PushBroker();
pusher.OnNotificationSent += pusher_OnNotificationSent;//发送成功事件
pusher.OnNotificationFailed += pusher_OnNotificationFailed;//发送失败事件
pusher.OnChannelCreated += pusher_OnChannelCreated;
pusher.OnChannelDestroyed += pusher_OnChannelDestroyed;
pusher.OnChannelException += pusher_OnChannelException;
pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged;
pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired;
pusher.OnNotificationRequeue += pusher_OnNotificationRequeue;
pusher.OnServiceException += pusher_OnServiceException;
//注册推送服务
byte[] certificateData = File.ReadAllBytes(@"E:\KenshinCui_Push.p12");
pusher.RegisterAppleService(new ApplePushChannelSettings(certificateData, "123"));
foreach (string token in deviceToken)
{
//给指定设备发送消息
pusher.QueueNotification(new AppleNotification()
.ForDeviceToken(token)
.WithAlert(message)
.WithBadge(1)
.WithSound("default"));
}
}
void pusher_OnServiceException(object sender, Exception error)
{
Console.WriteLine("消息发送失败,错误详情:" + error.ToString());
PersonalizeMessageBox.Show(this, "消息发送失败,错误详情:" + error.ToString(), "系统提示");
}
void pusher_OnNotificationRequeue(object sender, PushSharp.Core.NotificationRequeueEventArgs e)
{
Console.WriteLine("pusher_OnNotificationRequeue");
}
void pusher_OnDeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, PushSharp.Core.INotification notification)
{
Console.WriteLine("pusher_OnDeviceSubscriptionChanged");
}
void pusher_OnDeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, PushSharp.Core.INotification notification)
{
Console.WriteLine("pusher_OnDeviceSubscriptionChanged");
}
void pusher_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error)
{
Console.WriteLine("消息发送失败,错误详情:" + error.ToString());
PersonalizeMessageBox.Show(this, "消息发送失败,错误详情:" + error.ToString(), "系统提示");
}
void pusher_OnChannelDestroyed(object sender)
{
Console.WriteLine("pusher_OnChannelDestroyed");
}
void pusher_OnChannelCreated(object sender, PushSharp.Core.IPushChannel pushChannel)
{
Console.WriteLine("pusher_OnChannelCreated");
}
void pusher_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error)
{
Console.WriteLine("消息发送失败,错误详情:" + error.ToString());
PersonalizeMessageBox.Show(this, "消息发送失败,错误详情:"+error.ToString(), "系统提示");
}
void pusher_OnNotificationSent(object sender, PushSharp.Core.INotification notification)
{
Console.WriteLine("消息发送成功!");
PersonalizeMessageBox.Show(this, "消息发送成功!", "系统提示");
}
#endregion
}
}
| 方法 | 说明 |
| - (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject | 添加监听,参数: observer:监听者 selector:监听方法(监听者监听到通知后执行的方法) name:监听的通知名称 object:通知的发送者(如果指定nil则监听任何对象发送的通知) |
| - (id <NSObject>)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block | 添加监听,参数: name:监听的通知名称 object:通知的发送者(如果指定nil则监听任何对象发送的通知) queue:操作队列,如果制定非主队线程队列则可以异步执行block block:监听到通知后执行的操作 |
| - (void)postNotification:(NSNotification *)notification | 发送通知,参数: notification:通知对象 |
| - (void)postNotificationName:(NSString *)aName object:(id)anObject | 发送通知,参数: aName:通知名称 anObject:通知发送者 |
| - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo | 发送通知,参数: aName:通知名称 anObject:通知发送者 aUserInfo:通知参数 |
| - (void)removeObserver:(id)observer | 移除监听,参数: observer:监听对象 |
| - (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject | 移除监听,参数: observer:监听对象 aName:通知名称 anObject:通知发送者 |
//
// KCMainViewController.m
// NotificationCenter
//
// Created by Kenshin Cui on 14/03/27.
// Copyright (c) 2014年 cmjstudio. All rights reserved.
//
#import "KCMainViewController.h"
@interface KCMainViewController ()
@end
@implementation KCMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addObserverToNotificationCenter];
}
#pragma mark 添加监听
-(void)addObserverToNotificationCenter{
/*添加应用程序进入后台监听
* observer:监听者
* selector:监听方法(监听者监听到通知后执行的方法)
* name:监听的通知名称(下面的UIApplicationDidEnterBackgroundNotification是一个常量)
* object:通知的发送者(如果指定nil则监听任何对象发送的通知)
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];
/* 添加应用程序获得焦点的通知监听
* name:监听的通知名称
* object:通知的发送者(如果指定nil则监听任何对象发送的通知)
* queue:操作队列,如果制定非主队线程队列则可以异步执行block
* block:监听到通知后执行的操作
*/
NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification object:[UIApplication sharedApplication] queue:operationQueue usingBlock:^(NSNotification *note) {
NSLog(@"Application become active.");
}];
}
#pragma mark 应用程序启动监听方法
-(void)applicationEnterBackground{
NSLog(@"Application enter background.");
}
@end
//
// KCMainViewController.m
// NotificationCenter
//
// Created by Kenshin Cui on 14/03/27
// Copyright (c) 2014年 cmjstudio. All rights reserved.
//
#import "KCMainViewController.h"
#import "KCLoginViewController.h"
#define UPDATE_LGOGIN_INFO_NOTIFICATION @"updateLoginInfo"
@interface KCMainViewController (){
UILabel *_lbLoginInfo;
UIButton *_btnLogin;
}
@end
@implementation KCMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
-(void)setupUI{
UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(0, 100,320 ,30)];
label.textAlignment=NSTextAlignmentCenter;
label.textColor=[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1];
_lbLoginInfo=label;
[self.view addSubview:label];
UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
button.frame=CGRectMake(60, 200, 200, 25);
[button setTitle:@"登录" forState:UIControlStateNormal];
[button addTarget:self action:@selector(loginOut) forControlEvents:UIControlEventTouchUpInside];
_btnLogin=button;
[self.view addSubview:button];
}
-(void)loginOut{
//添加监听
[self addObserverToNotification];
KCLoginViewController *loginController=[[KCLoginViewController alloc]init];
[self presentViewController:loginController animated:YES completion:nil];
}
/**
* 添加监听
*/
-(void)addObserverToNotification{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLoginInfo:) name:UPDATE_LGOGIN_INFO_NOTIFICATION object:nil];
}
/**
* 更新登录信息,注意在这里可以获得通知对象并且读取附加信息
*/
-(void)updateLoginInfo:(NSNotification *)notification{
NSDictionary *userInfo=notification.userInfo;
_lbLoginInfo.text=userInfo[@"loginInfo"];
_btnLogin.titleLabel.text=@"注销";
}
-(void)dealloc{
//移除监听
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
登录界面KCLoginViewController.m:
//
// KCLoginViewController.m
// NotificationCenter
//
// Created by Kenshin Cui on 14/03/27.
// Copyright (c) 2014年 cmjstudio. All rights reserved.
//
#import "KCLoginViewController.h"
#define UPDATE_LGOGIN_INFO_NOTIFICATION @"updateLoginInfo"
@interface KCLoginViewController (){
UITextField *_txtUserName;
UITextField *_txtPassword;
}
@end
@implementation KCLoginViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
}
/**
* UI布局
*/
-(void)setupUI{
//用户名
UILabel *lbUserName=[[UILabel alloc]initWithFrame:CGRectMake(50, 150, 100, 30)];
lbUserName.text=@"用户名:";
[self.view addSubview:lbUserName];
_txtUserName=[[UITextField alloc]initWithFrame:CGRectMake(120, 150, 150, 30)];
_txtUserName.borderStyle=UITextBorderStyleRoundedRect;
[self.view addSubview:_txtUserName];
//密码
UILabel *lbPassword=[[UILabel alloc]initWithFrame:CGRectMake(50, 200, 100, 30)];
lbPassword.text=@"密码:";
[self.view addSubview:lbPassword];
_txtPassword=[[UITextField alloc]initWithFrame:CGRectMake(120, 200, 150, 30)];
_txtPassword.secureTextEntry=YES;
_txtPassword.borderStyle=UITextBorderStyleRoundedRect;
[self.view addSubview:_txtPassword];
//登录按钮
UIButton *btnLogin=[UIButton buttonWithType:UIButtonTypeSystem];
btnLogin.frame=CGRectMake(70, 270, 80, 30);
[btnLogin setTitle:@"登录" forState:UIControlStateNormal];
[self.view addSubview:btnLogin];
[btnLogin addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
//取消登录按钮
UIButton *btnCancel=[UIButton buttonWithType:UIButtonTypeSystem];
btnCancel.frame=CGRectMake(170, 270, 80, 30);
[btnCancel setTitle:@"取消" forState:UIControlStateNormal];
[self.view addSubview:btnCancel];
[btnCancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark 登录操作
-(void)login{
if ([_txtUserName.text isEqualToString:@"kenshincui"] && [_txtPassword.text isEqualToString:@"123"] ) {
//发送通知
[self postNotification];
[self dismissViewControllerAnimated:YES completion:nil];
}else{
//登录失败弹出提示信息
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"系统信息" message:@"用户名或密码错误,请重新输入!" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
[alertView show];
}
}
#pragma mark 点击取消
-(void)cancel{
[self dismissViewControllerAnimated:YES completion:nil];
}
/**
* 添加通知,注意这里设置了附加信息
*/
-(void)postNotification{
NSDictionary *userInfo=@{@"loginInfo":[NSString stringWithFormat:@"Hello,%@!",_txtUserName.text]};
NSLog(@"%@",userInfo);
NSNotification *notification=[NSNotification notificationWithName:UPDATE_LGOGIN_INFO_NOTIFICATION object:self userInfo:userInfo];
[[NSNotificationCenter defaultCenter] postNotification:notification];
//也可直接采用下面的方法
// [[NSNotificationCenter defaultCenter] postNotificationName:UPDATE_LGOGIN_INFO_NOTIFICATION object:self userInfo:userInfo];
}
@end
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有