Creating your First iOS App (User-to-User chat)

This guide walks you through how to build a new iOS Mobile app that will enable in-app user-to-user chat between platforms.

Create a new App

  1. Open Magnet Studio.

  2. Click the Create App button in the navigation bar.

  3. Enter a name for your app. Click Save to create your new app.


  4. Download MagnetMax.plist (from the Settings screen) and include in it in your new Xcode project.

  5. Add the Magnet Message library to your Xcode project with CocoaPods. See the CocoaPods Get Started guide for more information.

    source '' source '' platform :ios, '8.0' use_frameworks! pod 'MagnetMax', '~> 2.7' }

  6. Initialize the Magnet Message SDK.

    // In your AppDelegate @import MagnetMax; @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Configure MagnetMax NSString *configurationFile = [[NSBundle mainBundle] pathForResource:@"MagnetMax" ofType:@"plist"]; id <MMConfiguration> configuration = [[MMPropertyListConfiguration alloc] initWithContentsOfFile:configurationFile]; [MagnetMax configure:configuration]; // Your code ... return YES; } @end

  7. Register yourself as a Magnet Message User.

    MMUser *user = [[MMUser alloc] init]; user.firstName = @"Jane"; user.lastName = @"Doe"; = @""; user.userName = @"jane.doe";//; user.password = @"password"; [user register:^(MMUser *user) { NSLog(@"user = %@", user); } failure:^(NSError *error) { NSLog(@"error = %@", error.localizedDescription); }];

  8. Log in with the user created in the previous step, and initialize Magnet Message.

    NSString *username = @"jane.doe"; NSString *password = @"password"; NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone]; [MMUser login:credential success:^{ NSLog(@"currentUser = %@", [MMUser currentUser]); } failure:^(NSError *error) { NSLog(@"Login error = %@", error.localizedDescription); }];

  9. Get the current user after logging in.

    MMUser *currentUser = [MMUser currentUser];

  10. Get Users. For example, to find users with known user names, use the code example below.

    [MMUser usersWithUserNames:@[@"jane.doe",@"john.doe"] success:^(NSArray *users) { // do something } failure:^(NSError *error) { }];

  11. Create a chat channel with recipients. NOTE: In most cases the chat channel should be prviate. Only channel owners can invite people into the chat.

    // MMUser *johnDoe = ...; // MMUser *janeSmith = ...; NSSet <MMUser *> *recipients = [NSSet setWithArray:@[johnDoe, janeSmith]]; __block MMXChannel *myChatChannel; [MMXChannel createWithName:name summary:summary isPublic:NO publishPermissions:MMXPublishPermissionsSubscribers subscribers:recipients success:^(MMXChannel * _Nonnull channel) { myChatChannel = channel; } failure:^(NSError * _Nonnull error) { }];

  12. Send the message.

    NSDictionary *content = @{@"foo": @"bar"}; // Build the message MMXMessage *message = [MMXMessage messageToChannel:myChatChannel messageContent:content]; [myChatChannel publishMessage:message success:^{ // do something } failure:^(NSError * _Nonnull error) { // do something }];

  13. Register for a notification to receive the message and chat invitation. </a>

    - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // Indicate that you are ready to receive messages now! [MMX start]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessage:) name:MMXDidReceiveMessageNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveChannelInvite:) name:MMXDidReceiveChannelInviteNotification object:nil]; }

  14. Once MMX has started, you can continue to implement your notification code as shown below:

    - (void)didReceiveMessage:(NSNotification *)notification { MMXMessage *message = notification.userInfo[MMXMessageKey]; // Do something with the message } - (void)didReceiveChannelInvite:(NSNotification *)notification { MMXInvite *invite = notification.userInfo[MMXInviteKey]; // Do something with the invite } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:(BOOL)animated]; [[NSNotificationCenter defaultCenter] removeObserver:self]; }

  15. Invite more users into the chat using the same invitation process used in the Private Discussion Group.

  16. Get the chat history.

    int limit = 10; int offset = 0; NSDate *now = [NSDate date]; NSDate *anHourAgo = [now dateByAddingTimeInterval:-(60 * 60)]; BOOL ascending = NO; [myChatChannel messagesBetweenStartDate:anHourAgo endDate:now limit:limit offset:offset ascending:ascending success:^(int totalCount, NSArray<MMXMessage *> * _Nonnull messages) { } failure:^(NSError * _Nonnull error) { }];

  17. Get all chat recipients.

    MMXChannel *myChatChannel = ...; [myChatChannel subscribersWithLimit:100 offset:0 success:^(int totalCount, NSArray<MMUser *> * _Nonnull subscribers) { } failure:^(NSError * _Nonnull error) { }];

  18. Set up disconnection handling. A user can be redirected to the login screen on disconnect with the code below.

    - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDisconnect:) name:MMUserDidReceiveAuthenticationChallengeNotification object:nil]; } - (void)didDisconnect:(NSNotification *)notification { // Indicate that you are not ready to receive messages now! [MMX stop]; // Redirect to the login screen //When the user logs back in you will need to reinitialize MMX } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:(BOOL)animated]; [[NSNotificationCenter defaultCenter] removeObserver:self]; }

Advanced: Wakeup Users

We provide the capability to add a mechanism that notifies the app there is a pending incoming message to registerd users who are not currently online. This capability leverages the platform's push technology—in the case of iOS: APNS.

NOTE: Configuring APNS for your application is a prerequisite. Please see our detailed documentation on how to setup APNS for your application.

// In your AppDelegate @import MagnetMax; @implementation AppDelegate - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { //In the case of a silent notification use the following code to see if it is a wakeup notification if ([MMXRemoteNotification isWakeupRemoteNotification:userInfo]) { //Send local notification to the user or connect via MMXClient completionHandler(UIBackgroundFetchResultNewData); } else if ([MMXRemoteNotification isMMXRemoteNotification:userInfo]) { NSLog(@"userInfo = %@",userInfo); //Check if the message is designed to wake up the client [MMXRemoteNotification acknowledgeRemoteNotification:userInfo completion:^(BOOL success) { completionHandler(UIBackgroundFetchResultNewData); }]; } else { completionHandler(UIBackgroundFetchResultNoData); } } @end

Next Steps

See how to send and receive Rich Messages in your app.