我想从声云帐户中检索一些 private 曲目,我有声音云帐户的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”,
“scope”:“未过期”
}

我已经在使用声云sdk从声云艺术家获取 public 曲目,但是现在无法从我的声云帐户中获取 private 曲目。

最佳答案

该代码在我的某些项目中对我有用:

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

10-07 17:39