2009-06-28 9 views
5

Je retire mes cheveux sur celui-ci ... J'utilise la bibliothèque wrapper ASIHTTPRequest (http://allseeing-i.com/ASIHTTPRequest/) pour accéder au stockage Amazon S3. Je suis capable de me connecter très bien et de saisir une liste de seaux sans aucun problème. Ma frustration est d'essayer de transférer (PUT et/ou POST) un nouvel objet (une photo) dans un seau existant. Je suis la documentation d'Amazon à la lettre, (au moins je pense que je suis.) Mais rien ne semble fonctionner.Téléchargement vers Amazon S3 Services à partir de l'application iPhone

S'il vous plaît, quelqu'un m'aidera avant de sauter par la fenêtre. Je ne veux pas mourir. :-(

Merci d'avance pour toute aide que je peux obtenir.

L.

+0

Hmmmm - assez difficile à aider sans aucun détail au-delà de «ça ne marche pas». Qu'est-ce spécifiquement? Échoue de quelle manière? Code? Qu'avez-vous essayé? – Hunter

Répondre

12

Voici un exemple de base en utilisant PUT. Il est évident que vous devez utiliser une file d'attente plutôt que d'une requête synchrone dans le réel monde.

Si vous changez les en-têtes de AMZ, ne pas oublier de mettre à jour « » canonicalizedAmzHeaders selon les instructions d'Amazon.

#import "ASIHTTPRequest.h" 
#import <CommonCrypto/CommonHMAC.h> 

... 

- (void)testS3 
{ 
    NSString *filePath = @"/path/to/file"; 
    NSString *contentType = @"text/plain"; 
    NSString *bucket = @"mybucket"; 
    NSString *path = @"test"; 
    NSString *secretAccessKey = @"my-secret-access-key"; 
    NSString *accessKey = @"my-access-key"; 

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
    [dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss zzzz"]; 
    NSString *date = [dateFormatter stringFromDate:[NSDate date]]; 

    ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@.s3.amazonaws.com/%@",bucket,path]]] autorelease]; 
    [request setPostBodyFilePath:filePath]; 
    [request setShouldStreamPostDataFromDisk:YES]; 
    [request setRequestMethod:@"PUT"]; 

    [request addRequestHeader:@"x-amz-acl" value:@"private"]; 
    [request addRequestHeader:@"Content-Type" value:contentType]; 
    [request addRequestHeader:@"Date" value:date]; 

    NSString *canonicalizedAmzHeaders = @"x-amz-acl:private"; 
    NSString *canonicalizedResource = [NSString stringWithFormat:@"/%@/%@",bucket,path]; 
    NSString *stringToSign = [NSString stringWithFormat:@"PUT\n\n%@\n%@\n%@\n%@",contentType,date,canonicalizedAmzHeaders,canonicalizedResource]; 

    NSString *signature = [self base64forData:[self HMACSHA1withKey:secretAccessKey forString:stringToSign]]; 
    NSString *auth = [NSString stringWithFormat:@"AWS %@:%@",accessKey,signature]; 
    [request addRequestHeader:@"Authorization" value:auth]; 


    [request start]; 
    NSLog(@"%@",[request responseString]); 

} 


// Source: http://stackoverflow.com/questions/476455/is-there-a-library-for-iphone-to-work-with-hmac-sha-1-encoding 

- (NSData *)HMACSHA1withKey:(NSString *)key forString:(NSString *)string 
{ 
    NSData *clearTextData = [string dataUsingEncoding:NSUTF8StringEncoding]; 
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding]; 

    uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0}; 

    CCHmacContext hmacContext; 
    CCHmacInit(&hmacContext, kCCHmacAlgSHA1, keyData.bytes, keyData.length); 
    CCHmacUpdate(&hmacContext, clearTextData.bytes, clearTextData.length); 
    CCHmacFinal(&hmacContext, digest); 

    return [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH]; 
} 

//Source http://www.cocoadev.com/index.pl?BaseSixtyFour 

- (NSString *)base64forData:(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:NSASCIIStringEncoding freeWhenDone:YES] autorelease]; 
} 
+0

You Rock pokeb. Vraiment apprécier l'aide. Mon CanonicalizedAmzHeader était tout vilain. J'ai un autre problème cependant ... J'ai essayé "d'ajouter" la demande à une file d'attente et de commencer à partir de là mais en vain. Voici mon code: [networkQueue cancelAllOperations]; [demande ..... définitions vont ici]; [networkQueue addOperation: request]; [networkQueue go]; Quelles sont les choses à surveiller lorsque vous ajoutez une requête à une file d'attente? merci encore pour l'aide! L. –

+0

Avez-vous créé la file d'attente en premier? (par exemple: [self setNetworkQueue: [ASINetworkQueue queue]]) – pokeb

+0

Vous aviez raison à nouveau. Ma variable d'instance networkQueue n'a jamais été initialisée. Tu es l'homme. Vraiment apprécier l'aide. –

1

Il y a aussi la Connection Kit L'infrastructure Cocoa, qui est capable de télécharger des données vers différents services, y compris Amazon S3. Je suis sûr qu'il a quelques points de départ pour vous dans sa source.

11

Dans le cas où il est utile pour toute personne qui trouve cette question - Support de base S3 est maintenant intégré à ASIHTTPRequest:

http://allseeing-i.com/ASIHTTPRequest/S3

j'avais pensé à ajouter le support S3 pour les âges, mais votre question poussai il à l'avant de la file d'attente :)

+0

NICE! J'aime l'emballage. Je suis devenu ton plus grand fan. Continuez ce bon travail! –

+0

merci pour la jolie bibliothèque! :) –

Questions connexes