2013-06-27 50 views
3

我有以下代碼使用quickblox。我收到未經授權的錯誤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 

回答

1

我不知道你有這些證書

extendedAuthRequest.userLogin = @"testjk"; 
extendedAuthRequest.userPassword = @"jerry"; 
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); 
    } 
} 
0

我遇見這裏同樣的問題。我給了我做的方式。

  1. 錯誤未授權是user.login或user.password。
  2. user.login不能是電子郵件地址,而是您的登錄用戶名。這些我不知道爲什麼。
  3. user.password是電子郵件地址/用戶名密碼。
  4. 檢查這些信息在你的用戶列表中QuickBlox儀表板

希望這些說明將幫助。

+0

它適用於我 –

+0

這個答案似乎有點難以閱讀。請對其進行編輯以使其更易讀和清晰。使用文本格式可能會有所幫助(閱讀:http://stackoverflow.com/editing-help)。我認爲這對其他人更有幫助。 –

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': '[email protected]' }; 

    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)); 
     } 
    })}