Question

I want to retrieve some private tracks from sound cloud account, I have client_id, client_secret, username and password of the sound cloud account(from where I want to retrieve the tracks). I found following code from sound cloud docs which is in php, but I want to implement that in objective C i.e in 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'

output

{ "access_token": "04u7h-4cc355-70k3n", "scope": "non-expiring" }

I am already using sound cloud sdk to fetch the public tracks from sound cloud artist, but now unable to fetch the private tracks from my sound cloud account.

Was it helpful?

Solution 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];
}

This gives me non-expiring token, and advantage is I am using soundcloud sdk, that makes it litle easy

OTHER TIPS

This code worked for me in some my projects:

- (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];
}

Also it is need to set NSURLConnection Delegate Methods.

It's usual code:

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

And here SBJSON parser was used. You can use it or replace it with any other JSON-parser, but then you need to change code for parsing JSON, it's not hard:

- (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"];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top