NSString作为参数失败,但文字字符串有效吗?

时间:2014-02-17 19:34:23

标签: ios objective-c amazon-web-services

我从我的AWS服务器中提取了一系列歌曲名称。

我的下一步是使用其中一个歌曲名称作为请求中的参数来检索其可流式URL。

    //[1] Initialize the S3 Client.
    self.s3 = [[AmazonS3Client alloc] initWithAccessKey:@"blah" withSecretKey:@"blah"];
    self.s3.endpoint = [AmazonEndpoints s3Endpoint:US_WEST_2];



    //[2] Get an array of song names
    NSArray *song_array = [self.s3 listObjectsInBucket:@"blahblah"];
    NSLog(@"the objects are %@", song_array);


    //[3] Get a single song name from the array
    NSString *song1 = [[NSString alloc] init];
    song1 = (NSString *)[song_array objectAtIndex:1];
    NSLog(@"%@", song1);

    NSString * song2 =  @"Rap God.mp3";
    NSLog(@"%@", song2);


    //[4] Get the Song URL
    S3GetPreSignedURLRequest *gpsur = [[S3GetPreSignedURLRequest alloc] init];
    gpsur.key                     = song2;
    gpsur.bucket                  =@"soundshark";
    gpsur.expires                 = [NSDate dateWithTimeIntervalSinceNow:(NSTimeInterval) 3600]; 
    NSError *error;
    NSURL *url = [self.s3 getPreSignedURL:gpsur error:&error];
    NSLog(@"the url is %@", url);

Song2完美地作为参数gpsur.key。

但是,如果我使用song1作为参数,则会因错误

而失败
  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [S3ObjectSummary stringWithURLEncoding]:无法识别的选择器发送到实例0x175aef30

当我使用NSLog时,song1和song2都打印完全相同的字符串“Rap God.mp3”

为什么会出错?为什么我不能只使用数组中的字符串?它具有完全相同的值?

3 个答案:

答案 0 :(得分:1)

更改

NSString *song1 = [[NSString alloc] init];
song1 = (NSString *)[song_array objectAtIndex:1];
NSLog(@"%@", song1);

S3ObjectSummary *s3object = [song_array objectAtIndex:1];
NSString *song1 = [s3object description];
NSLog(@"%@", song1);

如果可行,最好更改

NSString *song1 = [s3object description];

NSString *song1 = [s3object etag];

NSString *song1 = [s3object key];

我不熟悉S3ObjectSummary所以我不能建议哪种变体更好。

答案 1 :(得分:1)

问题是“song1”实际上并不是NSString。以下表示您尝试在类S3WbjectSummary的对象上调用一个不存在的方法。这告诉你“song1”是一个S3SObjectSummary而不是NSString。

'-[S3ObjectSummary stringWithURLEncoding]: unrecognized selector sent to instance

要解决此问题,我找到了S3ObjectSummary的文档,该文档描述了如何使用属性“description”从此对象获取NSString值。 [S3ObjectSummary description]

http://docs.aws.amazon.com/AWSiOSSDK/latest/Classes/S3ObjectSummary.html#//api/name/description

因此,在您的情况下,NSString将是song1.description

要把这些放在一起,你得到以下结果。

//Grab the S3ObjectSummary from the array
    S3ObjectSummary *song1 = (S3ObjectSummary*)[song_array objectAtIndex:1];
    NSLog(@"%@", song1);

// Use the description property of S3ObjectSummary to get the string value.
    NSString *stringFromObjectSummary = song1.description;


    S3GetPreSignedURLRequest *gpsur = [[S3GetPreSignedURLRequest alloc] init];
    gpsur.key                     = stringFromObjectSummary;

答案 2 :(得分:0)

乍一看,您应该使用stringByAddingPercentEscapesUsingEncoding对网址中的不允许字符进行编码:

检查此link是否有编码目的。

另外,你应该尝试这样从数组元素构造一个字符串。

NSString *song1 = [NString stringWithFormat:@"%@", [song_array objectAtIndex:1]];
NSLog(@"%@", song1);
相关问题