1,引入MqttSDK.
2,在Appdelegare中引入头
#import "MQTTSession.h"
#import "MQTTViewController.h"
//定义主题
#define kTopic @"lichanghong"
//服务器ip
#define kIP @"192.168.2.204"
@interface SWAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (readonly, strong, nonatomic) NSString *currentUser;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
- (void)login;
- (void)connectToServer;
- (void)sendMessage:(NSString *)message toUser:(NSString *)toUser;
+ (SWAppDelegate *)shareInstance;
@end
//定义一属性
@interface SWAppDelegate ()
@property (nonatomic, strong) MQTTSession *session;
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
MQTTViewController *mqttVC = [[MQTTViewController alloc]init];
mqttVC.view.backgroundColor = [UIColor whiteColor];
self.window.rootViewController = mqttVC;
return YES;
}
所有实现代码都在MQTTViewController里
#import "MQTTSession.h"
#import "Message+Parser.h"
@implementation MQTTViewController
{
MQTTSession *session;
}
- (void)viewDidLoad {
[super viewDidLoad];
// //连接
session = [[MQTTSession alloc] initWithClientId:@"12345"];
[session setDelegate:self];
[session connectToHost:@"192.168.2.204" port:1883];
//
// [session publishDataAtLeastOnce:[@"publish data..." dataUsingEncoding:NSUTF8StringEncoding] onTopic:@"lichanghong"];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - MQtt Callback methods
- (void)session:(MQTTSession*)sender handleEvent:(MQTTSessionEvent)eventCode {
switch (eventCode) {
case MQTTSessionEventConnected:
[session subscribeTopic:@"lichanghong"];
NSLog(@"connected");
break;
case MQTTSessionEventConnectionRefused:
NSLog(@"connection refused");
break;
case MQTTSessionEventConnectionClosed:
NSLog(@"connection closed");
break;
case MQTTSessionEventConnectionError:
NSLog(@"connection error");
NSLog(@"reconnecting...");
// Forcing reconnection
[session connectToHost:kIP port:1883];
break;
case MQTTSessionEventProtocolError:
NSLog(@"protocol error");
break;
}
}
- (void)session:(MQTTSession*)sender newMessage:(NSData*)data onTopic:(NSString*)topic {
NSLog(@"new message, %lu bytes, topic=%@", (unsigned long)[data length], topic);
NSString *payloadString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"data: %@ %@", payloadString, data);
[Message parseMessage:data];
}