3

我使用 quickblox 有以下代码。

不幸的是,当我访问视图控制器时,我从 quickblox API 收到“未授权”错误。

我究竟做错了什么?

#import "QChatViewController.h"
#include "ChatMessageTableViewCell.h"

@interface QChatViewController ()

@end

@implementation QChatViewController

@synthesize opponent;
@synthesize currentRoom;
@synthesize messages;

@synthesize toolBar;
@synthesize sendMessageField;
@synthesize sendMessageButton;
@synthesize tableView;

#pragma mark -
#pragma mark View controller's lifecycle

- (id) initWithStartup: (NSDictionary *) _startup investor: (NSDictionary *) _investor chat_id: (NSInteger) _chat_id chat_name: (NSString *) _name
{ 
    self = [self initWithNibName: @"QChatViewController" bundle: nil];

    if(self)
    {
        startup = _startup;
        investor = _investor;

        startup_id = 0;
        investor_id = 0;

        if ([startup objectForKey: @"id"] &&
            [startup objectForKey: @"id"] != (id)[NSNull null])
        {
            startup_id = [[startup objectForKey: @"id"] intValue];
        }

        if ([investor objectForKey: @"id"] &&
            [investor objectForKey: @"id"] != (id)[NSNull null])
        {
            investor_id = [[investor objectForKey: @"id"] intValue];
        }

        past = 0;
        chat_id = _chat_id;

        self.title = _name;
        self.title = @"Chat";

        UIButton * button4 = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage * btnImage = [UIImage imageNamed: @"chatrightbtn.png"];
        [button4 setFrame:CGRectMake(-90.0f, 0.0f, btnImage.size.width, btnImage.size.height)];
        [button4 addTarget:self action:@selector(showSheet:) forControlEvents:UIControlEventTouchUpInside];
        [button4 setImage: btnImage forState:UIControlStateNormal];
        UIBarButtonItem *random1 = [[UIBarButtonItem alloc] initWithCustomView:button4];

        self.navigationItem.rightBarButtonItem = random1;
        self.navigationItem.leftBarButtonItem.title = @"";
    }

    return self;
}


- (void) viewWillAppear:(BOOL)animated
{

    [super viewWillAppear: animated];


    QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
    extendedAuthRequest.userLogin = @"testjk";
    extendedAuthRequest.userPassword = @"jerry";

    [QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];


}
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationController.navigationBarHidden = NO;


    if(chat_id >= 1) {
        NSString * roomName = [NSString stringWithFormat: @"%d", chat_id];
        [[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
    }

    messages = [[NSMutableArray alloc] init];


}

-(void) chatDidLogin{
    // You have successfully signed in to QuickBlox Chat
}

- (void)completedWithResult:(Result *)result{

    // Create session result
    if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){
        // You have successfully created the session
        QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;

        // Sign In to QuickBlox Chat
        QBUUser *currentUser = [QBUUser user];
        currentUser.ID = res.session.userID; // your current user's ID
        currentUser.password = @"jerry"; // your current user's password

        // set Chat delegate
        [QBChat instance].delegate = self;

        // login to Chat
        [[QBChat instance] loginWithUser:currentUser];

    }
}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    // leave room
    if(self.currentRoom){
        if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
            // back button was pressed.
            [[QBChat instance] leaveRoom:self.currentRoom];
            [[DataManager shared].rooms removeObject:self.currentRoom];
        }
    }
}

- (void)viewDidUnload{
    [self setToolBar:nil];
    [self setSendMessageField:nil];
    [self setSendMessageButton:nil];
    [self setTableView:nil];


    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
}

- (IBAction)sendMessage:(id)sender {

    if(self.sendMessageField.text.length == 0){
        return;
    }

    if(chat_id == 0)
    {
        NSString * sid = [NSString stringWithFormat: @"%d", startup_id];
        NSString * iid = [NSString stringWithFormat: @"%d", investor_id];
        NSString * pasts = [NSString stringWithFormat: @"%d", past];
        NSString * chat_ids = [NSString stringWithFormat: @"%d", chat_id];

        NSString * path_str = [NSString stringWithFormat: @"chats/?format=json"];
        NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                      sid, @"startup",
                                      iid, @"investor",
                                      pasts, @"past",
                                      chat_ids, @"conversation_id",
                                      @"avv7ejtaegxxk2wzgnymsj8xtm2tk9s4xgp6854r6dqn8bk6jjwux4g9dh9b", @"apikey",
                                      nil];

        [[API sharedInstance] postcommandWithParams:params
                                               path: path_str
                                       onCompletion:^(NSDictionary *json)
         {
             if(chat_id == 0)
             {
                 if ([json objectForKey: @"id"] &&
                     [json objectForKey: @"id"] != (id)[NSNull null])
                 {
                     chat_id = [[json objectForKey: @"id"] intValue];

                     if(chat_id >= 1) {
                         NSString * roomName = [NSString stringWithFormat: @"%d", chat_id];
                         [[QBChat instance] createOrJoinRoomWithName: roomName membersOnly:YES persistent:NO];
                     }

                     [[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];

                     // reload table
                     [self.tableView reloadData];

                     // hide keyboard & clean text field
                     [self.sendMessageField resignFirstResponder];
                     [self.sendMessageField setText:nil];
                 }
             }
         }];
    }
    else
    {
        [[QBChat instance] sendMessage:self.sendMessageField.text toRoom:self.currentRoom];

            // reload table
        [self.tableView reloadData];

        // hide keyboard & clean text field
        [self.sendMessageField resignFirstResponder];
        [self.sendMessageField setText:nil];
    }
}

-(void)keyboardShow{
    CGRect rectFild = self.sendMessageField.frame;
    rectFild.origin.y -= 215;

    CGRect rectButton = self.sendMessageButton.frame;
    rectButton.origin.y -= 215;

    [UIView animateWithDuration:0.25f
                     animations:^{
                         [self.sendMessageField setFrame:rectFild];
                         [self.sendMessageButton setFrame:rectButton];
                     }
     ];
}

-(void)keyboardHide{
    CGRect rectFild = self.sendMessageField.frame;
                         rectFild.origin.y += 215;
    CGRect rectButton = self.sendMessageButton.frame;
                         rectButton.origin.y += 215;

    [UIView animateWithDuration:0.25f
                     animations:^{
                         [self.sendMessageField setFrame:rectFild];
                         [self.sendMessageButton setFrame:rectButton];
                     }
     ];
}


#pragma mark - 
#pragma mark TextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self keyboardShow];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [self keyboardHide];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField setText:nil];
    [textField resignFirstResponder];
    return YES;
}


#pragma mark -
#pragma mark TableViewDataSource & TableViewDelegate

static CGFloat padding = 20.0;
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MessageCellIdentifier";


    // Create cell
    ChatMessageTableViewCell *cell = (ChatMessageTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ChatMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.userInteractionEnabled = NO;


    // Message
    QBChatMessage *messageBody = [messages objectAtIndex:[indexPath row]];

    // set message's text
    NSString *message = [messageBody text];
    cell.message.text = message;

    // message's datetime
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: @"yyyy-mm-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
    NSString *time = [formatter stringFromDate:messageBody.datetime];


    CGSize textSize = { 260.0, 10000.0 };
    CGSize size = [message sizeWithFont:[UIFont boldSystemFontOfSize:13]
                      constrainedToSize:textSize
                          lineBreakMode:UILineBreakModeWordWrap];
    size.width += (padding/2);


    // Left/Right bubble
    UIImage *bgImage = nil;
    if ([[[DataManager shared] currentUser] ID] == messageBody.senderID || self.currentRoom) {

        bgImage = [[UIImage imageNamed:@"orange.png"] stretchableImageWithLeftCapWidth:24  topCapHeight:15];

        [cell.message setFrame:CGRectMake(padding, padding*2, size.width+padding, size.height+padding)];

        [cell.backgroundImageView setFrame:CGRectMake( cell.message.frame.origin.x - padding/2,
                                              cell.message.frame.origin.y - padding/2,
                                              size.width+padding, 
                                              size.height+padding)];

        cell.date.textAlignment = UITextAlignmentLeft;
        cell.backgroundImageView.image = bgImage;

        if(self.currentRoom){
            cell.date.text = [NSString stringWithFormat:@"%d %@", messageBody.senderID, time];
        }else{
            cell.date.text = [NSString stringWithFormat:@"%@ %@", [[[DataManager shared] currentUser] login], time];
        }

    } else {

        bgImage = [[UIImage imageNamed:@"aqua.png"] stretchableImageWithLeftCapWidth:24  topCapHeight:15];

        [cell.message setFrame:CGRectMake(320 - size.width - padding,
                                                     padding*2, 
                                                     size.width+padding, 
                                                     size.height+padding)];

        [cell.backgroundImageView setFrame:CGRectMake(cell.message.frame.origin.x - padding/2,
                                              cell.message.frame.origin.y - padding/2,
                                              size.width+padding, 
                                              size.height+padding)];

        cell.date.textAlignment = UITextAlignmentRight;
        cell.backgroundImageView.image = bgImage;
        cell.date.text = [NSString stringWithFormat:@"%@ %@", self.opponent.login, time];
    }

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.messages count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    QBChatMessage *chatMessage = (QBChatMessage *)[messages objectAtIndex:indexPath.row];
    NSString *text = chatMessage.text;
    CGSize  textSize = { 260.0, 10000.0 };
    CGSize size = [text sizeWithFont:[UIFont boldSystemFontOfSize:13]
                  constrainedToSize:textSize 
                      lineBreakMode:UILineBreakModeWordWrap];

    size.height += padding;
    return size.height+padding+5;
}


#pragma mark -
#pragma mark QBChatDelegate

// Did receive 1-1 message
- (void)chatDidReceiveMessage:(QBChatMessage *)message{

    [self.messages addObject:message];

    // save message to cache if this 1-1 chat
    if (self.opponent) {
        [[DataManager shared] saveMessage:[NSKeyedArchiver archivedDataWithRootObject:messages]
                  toHistoryWithOpponentID:self.opponent.ID];
    }

    // reload table
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

// Did receive message in room
- (void)chatRoomDidReceiveMessage:(QBChatMessage *)message fromRoom:(NSString *)roomName{
    // save message
    [self.messages addObject:message];

    // reload table
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[messages count]-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

// Fired when you did leave room
- (void)chatRoomDidLeave:(NSString *)roomName{
    NSLog(@"Chat Controller chatRoomDidLeave");
}

// Called in case changing occupant
- (void)chatRoomDidChangeOnlineUsers:(NSArray *)onlineUsers room:(NSString *)roomName{
    NSLog(@"chatRoomDidChangeOnlineUsers %@, %@",roomName, onlineUsers);
}

- (void)chatRoomDidEnter:(QBChatRoom *)room{
    NSLog(@"Private room %@ was created", room.name);

    // You have to retain created room if this is temporary room. In other cases room will be destroyed and all occupants will be disconnected from room
    self.currentRoom =  room;

    // Add users to this room

    NSInteger user_id = [[[[API sharedInstance] user] objectForKey: @"id"] intValue];
    NSNumber *me = [NSNumber numberWithInt: user_id];
    NSArray *users = [NSArray arrayWithObjects: me, nil];

    [[QBChat instance] addUsers:users toRoom:room];
}

@end
4

4 回答 4

1

我不确定您是否有拥有这些凭据的用户

 extendedAuthRequest.userLogin = @"testjk";
 extendedAuthRequest.userPassword = @"jerry";
于 2013-07-01T10:10:50.637 回答
0

我首先检查用户是否存在或没有像这样修改您的代码...

//your code
.....

- (void) viewWillAppear:(BOOL)animated
{

    [super viewWillAppear: animated];
    //Create extended session request with user authorization
    QBASessionCreationRequest *extendedAuthRequest = [QBASessionCreationRequest request];
    //Check user exist or not
    if(self.currentQBUser){
        extendedAuthRequest.userLogin = @"testjk";
        extendedAuthRequest.userPassword = @"testjk";
    }
    [QBAuth createSessionWithExtendedRequest:extendedAuthRequest delegate:self];
}

........


- (void)completedWithResult:(Result *)result{

    // Create session result
    if(result.success && [result isKindOfClass:QBAAuthSessionCreationResult.class]){

          // Register new user
            self.currentQBUser =  [[QBUUser alloc] init];
            user.fullName = @"Your Name";
            user.login = @"testjk";
            user.password = @"testjk";
            user.tags = [NSMutableArray arrayWithObject:@"Chat"];
            // Create user
            [QBUsers signUp:user delegate:self];

        // You have successfully created the session
        QBAAuthSessionCreationResult *res = (QBAAuthSessionCreationResult *)result;

} else if([result isKindOfClass:[QBUUserLogInResult class]]){

        if(result.success){
    QBUUserLogInResult *res = (QBUUserLogInResult *)result;
            //Now login to chat
        // Sign In to QuickBlox Chat
        QBUUser *currentUser = res.user;
        currentUser.ID = @"testjk; // your current user's ID
        currentUser.password = @"testjk"; // same as user id

        // set Chat delegate
        [QBChat instance].delegate = self;

        // login to Chat
        [[QBChat instance] loginWithUser:currentUser];
        }
    }
       if (result.errors.count && (401 != result.status))
    {
        NSLog(@"QBErrors: %@",result.errors);
    }
}
于 2013-11-22T20:52:47.770 回答
0

我在这里遇到了同样的问题。我给出了我制作它的方式。

  1. 错误未授权是 user.login 或 user.password。
  2. user.login 不能是电子邮件地址,而是您的登录用户名。这些我不知道为什么。
  3. user.password 是电子邮件地址/用户名密码。
  4. 在 QuickBlox 仪表板的用户列表中检查这些信息

希望这些说明会有所帮助。

于 2015-09-09T04:16:29.557 回答
0
use quickblox.min.js

var QBApp = {
    appId: 123,
    authKey: 'dfdgfd44444',
    authSecret: 'dffdgfdg455445'
};

$(document).ready(function () {
    QB.init(QBApp.appId, QBApp.authKey, QBApp.authSecret);

    QB.createSession(function (err, result) {
        console.log('Session create callback', err, result);
    });
})


function addUser() {

    var pwd, ctr, data;
    ctr = document.getElementById(myForm.password);
    pwd = ctr.value;


    var params = { 'login': 'Rajesh', 'password': 'Pass@123' };

    alert(params)
    QB.users.create(params, function (err, user) {
        debugger;

        if (user) {
            alert('Done')
            //$('#output_place').val(JSON.stringify(user));
        } else {
            alert('Error')
            //$('#output_place').val(JSON.stringify(err));
        }
    })}
于 2016-06-16T06:35:56.913 回答