XMPP iOS:无法连接 openfire 服务器

Posted

技术标签:

【中文标题】XMPP iOS:无法连接 openfire 服务器【英文标题】:XMPP iOS: unable to connect openfire server 【发布时间】:2014-07-31 15:28:22 【问题描述】:

我使用此链接中的教程开发 ios XMPP 应用程序 >>> http://code.tutsplus.com/tutorials/building-a-jabber-client-for-ios-xmpp-setup--mobile-7190

现在我运行我的项目,它没有连接到我的 openfire 服务器,但没有显示错误。我听说一些开发人员通过在此链接中的 iOS 客户端中“启用”SSL 证书解决了相关问题 >>> Unable to connect openfire server using ios client。我必须启用它吗?以及如何启用它?

这个问题花了我一周的时间,所以我决定在 *** 上发帖。

这是我的“JabberClientAppDelegate.m”

//
//  AppDelegate.m
//  JabberClient
//
//  Created by Lance on 7/30/14.
//  Copyright (c) 2014 Lance. All rights reserved.
//

#import "JabberClientAppDelegate.h"

#import "SMBuddyListViewController.h"

@interface JabberClientAppDelegate()

- (void)setupStream;
- (void)goOnline;
- (void)goOffline;

@end

@implementation JabberClientAppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize chatDelegate;
@synthesize messageDelegate;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    SMBuddyListViewController *masterViewController = [[SMBuddyListViewController alloc] initWithNibName:@"SMBuddyListViewController" bundle:nil];
    self.viewController = masterViewController;
    self.window.rootViewController = self.viewController;

    [self.window makeKeyAndVisible];
    return YES;


- (void)xmppStreamDidConnect:(XMPPStream *)sender 

    // connection to the server successful
    isOpen = YES;
    NSError *error = nil;
    [[self xmppStream] authenticateWithPassword:password error:&error];



- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender 

    // authentication successful
    [self goOnline];



- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 

    // message received
    NSString *msg = [[message elementForName:@"body"] stringValue];
    NSString *from = [[message attributeForName:@"from"] stringValue];

    NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
    [m setObject:msg forKey:@"msg"];
    [m setObject:from forKey:@"sender"];

    [_messageDelegate newMessageReceived:m];



- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence 

    NSString *presenceType = [presence type]; // online/offline
    NSString *myUsername = [[sender myJID] user];
    NSString *presenceFromUser = [[presence from] user];

    if (![presenceFromUser isEqualToString:myUsername]) 

        if ([presenceType isEqualToString:@"available"]) 

            [_chatDelegate newBuddyOnline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"localhost"]];

         else if ([presenceType isEqualToString:@"unavailable"]) 

            [_chatDelegate buddyWentOffline:[NSString stringWithFormat:@"%@@%@", presenceFromUser, @"localhost"]];

        

    


- (void)setupStream 
    xmppStream = [[XMPPStream alloc] init];
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];



- (void)applicationWillResignActive:(UIApplication *)application 

    [self disconnect];



- (void)applicationDidBecomeActive:(UIApplication *)application 
    [xmppStream setHostName:@"localhost"];
    [xmppStream setHostPort:5222];


- (void)goOnline 
    XMPPPresence *presence = [XMPPPresence presence];
    [[self xmppStream] sendElement:presence];


- (void)goOffline 
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [[self xmppStream] sendElement:presence];


- (BOOL)connect 

    [self setupStream];

    NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userID"];
    NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:@"userPassword"];

    if (![xmppStream isDisconnected]) 
        return YES;
    

    if (jabberID == nil || myPassword == nil) 

        return NO;
    

    [xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
    password = myPassword;

    NSError *error = nil;
    if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                            message:[NSString stringWithFormat:@"Can't connect to server %@", nil]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];

        return NO;
    

    if(![xmppStream isConnected])
        NSLog(@"connected");
    
    //[[self xmppStream] authenticateAnonymously:&error];
    [self xmppStreamDidAuthenticate:xmppStream];
    return YES;


- (void)disconnect 

    [self goOffline];
    [xmppStream disconnect];



- (void)applicationDidEnterBackground:(UIApplication *)application

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.


- (void)applicationWillEnterForeground:(UIApplication *)application

    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.




- (void)applicationWillTerminate:(UIApplication *)application

    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];


- (void)saveContext

    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) 
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) 
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
         
    


#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext

    if (_managedObjectContext != nil) 
        return _managedObjectContext;
    

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) 
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    
    return _managedObjectContext;


// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel

    if (_managedObjectModel != nil) 
        return _managedObjectModel;
    
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JabberClient" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;


// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

    if (_persistentStoreCoordinator != nil) 
        return _persistentStoreCoordinator;
    

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JabberClient.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) 
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.


         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES

         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
        

    return _persistentStoreCoordinator;


#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];


@end

如果代码太多,我很抱歉,我是 iOS 开发和 XMPP 的初学者,请检查我的错误并指导我如何解决,我将不胜感激,谢谢。

【问题讨论】:

【参考方案1】:

您忘记设置服务器的端口号和主机名。

试试这个。

- (BOOL)connect 

        [self setupStream];

    // set openfire server host name and port number to connect 
    [self.xmppStream setHostName:@"serverHostName"];
    [self.xmppStream setHostPort:@"serverPortNumber"];

        NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:@"userID"];
        NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:@"userPassword"];

        if (![xmppStream isDisconnected]) 
            return YES;
        

        if (jabberID == nil || myPassword == nil) 

            return NO;
        


        [xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
        password = myPassword;

        NSError *error = nil;
        if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                message:[NSString stringWithFormat:@"Can't connect to server %@", nil]
                                                               delegate:nil
                                                      cancelButtonTitle:@"Ok"
                                                      otherButtonTitles:nil];
            [alertView show];

            return NO;
        



        return YES;
    

【讨论】:

以上是关于XMPP iOS:无法连接 openfire 服务器的主要内容,如果未能解决你的问题,请参考以下文章

XMPP之openfire无法启动

XMPP 聊天服务器未在 iOS 设备上连接。在模拟器上完美工作

无法使用 HTTP 绑定连接到 XMPP 服务器(openfire)

如何同步xmpp服务器openfire用户和iOS APP用户

iOS xmpp协议实现聊天之openfire的服务端配置

使用 Openfire 中的用户服务通过 iOS 的 xmpp 框架注册新用户