2014-04-10 115 views
1

我想從聲音雲帳戶檢索一些私人音樂,我有client_id,client_secret,用戶名和密碼的聲音雲帳戶(我想從中檢索曲目)。 我從php中找到了來自聲音雲文檔的代碼,但是我想在Objective C中實現它,即在iOS中。從聲音雲獲取訪問令牌?

$ curl -X POST "https://api.soundcloud.com/oauth2/token" \\ 
      -F 'client_id=YOUR_CLIENT_ID' \\ 
      -F 'client_secret=YOUR_CLIENT_SECRET' \\ 
      -F 'grant_type=authorization_code' \\ 
      -F 'redirect_uri=http://yourapp.com/soundcloud/oauth-callback' \\ 
      -F 'code=0000000EYAA1CRGodSoKJ9WsdhqVQr3g' 

輸出

{ 「的access_token」: 「04u7h-4cc355-70k3n」, 「範圍」: 「非過期」 }

我已經使用聲音雲SDK來從聲音雲端藝術家處獲取公開曲目,但現在無法從我的聲音雲帳戶中獲取私人曲目。

回答

2
+ (void)getAccessTokenWithCompletion:(callBackResponse)completion 
{ 
    NSString *BaseURI = @"https://api.soundcloud.com"; 
    NSString *OAuth2TokenURI = @"/oauth2/token"; 

    NSString *requestURL = [BaseURI stringByAppendingString:OAuth2TokenURI]; 

    SCRequestResponseHandler handler; 
    handler = ^(NSURLResponse *response, NSData *data, NSError *error) { 
     NSError *jsonError = nil; 
     NSJSONSerialization *jsonResponse = [NSJSONSerialization 
              JSONObjectWithData:data 
              options:0 
              error:&jsonError]; 
     if (!jsonError) 
     { 
      NSLog(@"output of getToken\n%@",jsonResponse); 
      NSDictionary* serverResponse = (NSDictionary*)jsonResponse; 
      if ([serverResponse objectForKey:@"access_token"]) 
      { 
       accessToken = [serverResponse objectForKey:@"access_token"]; 
       [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:SC_ACCESS_TOKEN_KEY]; 
       NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:accessToken,SC_ACCESS_TOKEN_KEY,nil]; 
       completion(dict); 
      } 
      else 
       completion(nil); 
     } 
    }; 


    NSMutableDictionary *parameter=[[NSMutableDictionary alloc]init]; 
    [parameter setObject:@"password" forKey:@"grant_type"]; 
    [parameter setObject:CLIENT_ID forKey:@"client_id"]; 
    [parameter setObject:CLIENT_SECRET forKey:@"client_secret"]; 
    [parameter setObject:CLIENT_USERNAME forKey:@"username"]; 
    [parameter setObject:CLIENT_PASSWORD forKey:@"password"]; 
    [parameter setObject:@"non-expiring" forKey:@"scope"]; 


    [SCRequest performMethod:SCRequestMethodPOST 
        onResource:[NSURL URLWithString:requestURL] 
      usingParameters:parameter 
       withAccount:nil 
     sendingProgressHandler:nil 
      responseHandler:handler]; 
} 

這使我永不過期的令牌,和優點是我正在使用soundcloud sdk,這使它容易起來

2

這段代碼在我的一些項目,爲我工作:

- (void)getToken { 
    NSString *BaseURI = @"https://api.soundcloud.com"; 
    NSString *OAuth2TokenURI = @"/oauth2/token"; 

    NSString *requestURL = [BaseURI stringByAppendingString:OAuth2TokenURI]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL] 
                 cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
                timeoutInterval:60.0f]; 

    NSString *requestBody = @"grant_type=password"; 
    requestBody = [requestBody stringByAppendingFormat:@"&client_id=%@", OAuth2ClientID]; 
    requestBody = [requestBody stringByAppendingFormat:@"&client_secret=%@", OAuth2ClientSecret]; 
    requestBody = [requestBody stringByAppendingFormat:@"&username=%@", userName]; 
    requestBody = [requestBody stringByAppendingFormat:@"&password=%@", userPassword]; 

    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:@"OAuth" forHTTPHeaderField:@"Authorization"]; 
    [request setValue:[NSString stringWithFormat:@"%d", [requestBody length]] forHTTPHeaderField:@"Content-Length"]; 

    [request setHTTPBody:[requestBody dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSURLConnection *tokenURLConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 
    self.receivedData = [NSMutableData data]; 
} 

此外,它是需要設置NSURLConnection的委託方法。

這是通常的代碼:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData { 
    [self.receivedData appendData:theData]; 
} 

這裏使用SBJSON解析器。你可以用它或與任何其他JSON解析器代替它,但你需要更改代碼的解析JSON,它並不難:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    NSString *accessToken; 
    NSString *jsonString = [[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] autorelease]; 
    SBJsonParser *jsonParser = [[[SBJsonParser alloc] init] autorelease]; 
    serverResponse = [jsonParser objectWithString:jsonString]; 

    if ([serverResponse objectForKey:@"access_token"]) { 
     accessToken = [serverResponse objectForKey:@"access_token"]; 
    } 
} 
+0

如果我授予grant_type = authorization_code或grant_type = password,那麼我無法獲取non_expiring訪問令牌事件。 – prabhu

+0

是的。但是,你想要什麼 - 玩軌道或有沒有過期的令牌? –

+0

是的,爲了播放音軌,每次都沒有獲取/刷新令牌,我找到了使用SoundCloud ios sdk的答案,它與你的答案几乎相似,差異在於他們將他們的類稱爲api,感謝Sergey提供的快速響應和幫助。 – prabhu