2009-09-08 7 views

Répondre

1

Il devrait y avoir absolument pas besoin de faire ça. À un niveau élevé, Cocoa fournit NSURLConnection qui fera l'authentification HTTP. Sinon, les API CFHTTP fournissent un accès de niveau inférieur.

+0

-1: Bien que NSURLConnection et CFHTTPMessageRef aient un accès interne au codage/décodage base64, ce qu'ils utilisent n'est pas accessible. –

+0

Pourriez-vous s'il vous plaît fournir un exemple avec une demande synchrone. Ce serait excellent si je pouvais le faire en utilisant seulement la classe NSURLConnection. – chaimp

+0

Eh bien, je conseillerais généralement contre les connexions synchrones. Utilisez l'API asynchrone et implémentez la méthode -connection: didReceiveAuthenticationChallenge: delegate. Si vous êtes absolument désespéré d'utiliser l'API synchrone, construisez l'URL afin qu'elle contienne le nom d'utilisateur et le mot de passe. –

1

Il existe quelques variantes de ce flottant qui étendent NSString ou NSData en utilisant les catégories Objective-C.

est ici un exemple que je l'ai ajouté à ma boîte à outils "utilitaires":

tête:

#import <Foundation/NSString.h> 

@interface NSString (Utilities) 

+ (NSString *) base64StringFromData:(NSData *)data; 

@end  

Mise en œuvre:

#import "NSString+Utilities.h" 

@implementation NSString (Utilities) 

+ (NSString *) base64StringFromData:(NSData *)data { 
    static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

    if ([data length] == 0)  
    return @""; 

    char *characters = malloc((([data length] + 2)/3) * 4); 
    if (characters == NULL) 
    return nil; 
    NSUInteger length = 0; 

    NSUInteger i = 0; 
    while (i < [data length]) { 
    char buffer[3] = {0,0,0}; 
    short bufferLength = 0; 
    while (bufferLength < 3 && i < [data length]) 
     buffer[bufferLength++] = ((char *)[data bytes])[i++]; 

    // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary. 
    characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2]; 
    characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)]; 

    if (bufferLength > 1) 
     characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)]; 
    else characters[length++] = '='; 

    if (bufferLength > 2) 
     characters[length++] = encodingTable[buffer[2] & 0x3F]; 
    else characters[length++] = '=';   
    } 

    return [[[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSUTF8StringEncoding freeWhenDone:YES] autorelease]; 
} 

@end 

Exemple d'utilisation:

NSString *inputString = @"myInputString"; 
NSLog(@"%@", [NSString base64StringFromData:[inputString dataUsingEncoding:NSUTF8StringEncoding]]); 
Questions connexes