使用的SoundCloud API在iOS上载轨道 [英] Upload tracks using SoundCloud API on iOS

查看:212
本文介绍了使用的SoundCloud API在iOS上载轨道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传MP3文件的SoundCloud,使用HTTP方法。我收到没有错误,但该文件没有出现在的SoundCloud上传。

我使用的是的multipart / form-data的请求

这是如何我目前正在进行。(我已经做了连接,授权,我知道我的用户ID)

 的NSString * URL = [的NSString stringWithFormat:@\"http://api.soundcloud.com/tracks.json?client_id=%@&user_id=%@&title=%@&tag_list=%@&sharing=%@&oauth_token=%@\",SOUNDCLOUD_CLIENT_ID, inputData [@user_ID的],inputData [@称号],inputData [@tag_list],inputData [@分享],ACCESS_TOKEN]
NSMutableURLRequest *请求= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
request.HTTPMethod = @POST;* NSString的边界= @的SoundCloud
NSMutableData *体= [NSMutableData数据]
[机构appendData:[[的NSString stringWithFormat:@\\ N - %@ \\ n,边界] dataUsingEncoding:NSUTF8StringEncoding]];
[机构appendData:[[的NSString stringWithFormat:@内容处置:表格数据;名称= \\asset_data \\;文件名= \\%@ \\\\ n,@我的文件name.mp3] dataUsingEncoding:NSUTF8StringEncoding]];
[机构appendData:[@内容类型:音频/ MPEG \\ n \\ ndataUsingEncoding:NSUTF8StringEncoding];
NSData的* audioData = [NSData的dataWithContentsOfFile:[一个NSBundle mainBundle] pathForResource:@无题ofType:@MP3]];
[机构appendData:[NSData的dataWithData:audioData]];
[机构appendData:[[的NSString stringWithFormat:@\\ N - %@,边界] dataUsingEncoding:NSUTF8StringEncoding]];request.HTTPBody =身体;[申请的setValue:[的NSString stringWithFormat:@%路德(无符号长)的车身长度] forHTTPHeaderField:@内容长度];
[申请的addValue:[的NSString stringWithFormat:@的multipart / form-data的;边界=%@,边界] forHTTPHeaderField:@内涵式];
request.timeoutInterval = 30;
self.connection = [[NSURLConnection的页头] initWithRequest:要求委托:自我];
[self.connection开始];

.MP3 文件实际上是我搜​​索,让audioData有合适的内容。
我收到一个200 HTTP响应code:

  NSHTTPURLResponse:{网址: https://api.soundcloud.com/tracks.json?client_id=[...]&user_id=[...]&title=dgd&tag_list=wgn&sharing=public&oauth_token=[...] } {状态code:200,头{访问控制允许报头=接受,授权,内容类型,起源;
访问控制允许的方法=GET,PUT,POST,DELETE
访问控制允许来源=*;
访问控制展露-头=日期;
缓存控制=私人,最大年龄= 0,必重新验证;
内容编码= gzip的;
内容类型=应用/ JSON的;字符集= UTF-8;
日期=星期一,2014年12月8日15时58分57秒格林尼治标准​​时间;
ETAG =\\66cc86baea454001c9572594b9caeea0 \\;
服务器=AM / 2;
设置Cookie=_session_auth_key = \\LdrvaLfDKfaGihR714EaihOotlo = \\;
传输编码=身份;
}}

然后,将响应JSON是包含在我的帐户中的所有曲目列表的数组。没有错误,但没有文件被上传。同一种反应是由模拟器和设备获得的。
任何建议都欢迎。

P.S。我也试过POST请求改变身体和内容类型是这样,但没有工作的结果:

 的NSDictionary *体= @ {@asset_data:[[NSData的dataWithContentsOfFile:[一个NSBundle mainBundle] pathForResource:@无题ofType:@MP3]] base64En codedStringWithOptions:0]};
NSData的* bodyData = [NSJSONSerialization dataWithJSONObject:身体选项:0错误:&放大器;错误]
request.HTTPBody = bodyData;
[申请的addValue:@应用程序/ JSONforHTTPHeaderField:@内涵式];


解决方案

我现在有工作code上传一首歌曲用的NSURLRequest。我希望这可以帮助你。

   - (无效)uploadTrackTitled:(* NSString的)标题withPath:(* NSString的)trackPath {
    NSURLSession * urlSession = [NSURLSession sharedSession]
    *的NSURLRequest =的URLRequest [个体经营getURLRequest:标题withAudioPath:trackPath];    NSURLSessionDataTask * dataTask = [urlSession dataTaskWithRequest:的URLRequest completionHandler:^(NSData的*数据,NSURLResponse *响应,NSError *错误){
        NSHTTPURLResponse * HTT presponse =(NSHTTPURLResponse *)响应;
        的NSLog(@返回:LD%,(长)HTT presponse.status code);        如果(数据){
            * NSString的stringResponse = [[NSString的页头] initWithData:数据编码:NSUTF8StringEncoding];
            的NSLog(@%@,stringResponse);
        }        如果(错误){
            的NSLog(@%@,[错误localizedDescription]);
        }
    }];    [dataTask简历]
} - (*的NSURLRequest)getURLRequest:(* NSString的)标题withAudioPath:(* NSString的)audioPath {
    CFUUIDRef UUID = CFUUIDCreate(NULL);
    * NSString的边界=(__bridge_transfer的NSString *)CFUUIDCreateString(NULL,UUID);
    CFRelease(UUID);
    NSMutableURLRequest *请求= [[NSMutableURLRequest页头] initWithURL:[NSURL URLWithString:@https://api.soundcloud.com/tracks]];    [要求setHTTPMethod:@POST];
    [要求setHTTPBody:[个体经营getPostData:self.scToken withBoundary:边界andTitle:标题withAudioPath:audioPath]];    * NSString的的contentType = [的NSString stringWithFormat:@的multipart / form-data的;边界=%@,边界]    [申请的setValue:contentType中forHTTPHeaderField:@的Content-Type];    返回请求;
} - (NSData的*)getPostData:(* NSString的)令牌withBoundary:(* NSString的)边界andTitle:(* NSString的)标题withAudioPath:(* NSString的)audioPath {
    * NSString的bo​​undaryStart = [的NSString stringWithFormat:@ - %@ \\ r \\ n,边界]
    * NSString的bo​​undaryEnd = [的NSString stringWithFormat:@\\ r \\ n - %@ - \\ r \\ n,边界]
    NSMutableData * bodyData = [[NSMutableData的alloc]初始化];    //添加令牌
    *的NSMutableString = tokenSection [的NSMutableString stringWithString:boundaryStart];
    [tokenSection appendFormat:@内容处置:表格数据;名称= \\组oauth_token \\\\ r \\ n \\ r \\ n];
    [tokenSection appendFormat:@%@ \\ r \\ n,令牌]
    [bodyData appendData:[tokenSection dataUsingEncoding:NSUTF8StringEncoding]];    //曲目标题
    *的NSMutableString = titleSection [的NSMutableString stringWithString:boundaryStart];
    [titleSection appendFormat:@内容处置:表格数据;名称= \\跟踪[标题] \\\\ r \\ n \\ r \\ n];
    [titleSection appendFormat:@%@ \\ r \\ n,标题]
    [bodyData appendData:[titleSection dataUsingEncoding:NSUTF8StringEncoding]];    //添加音频文件
    NSData的* trackData = [NSData的dataWithContentsOfFile:audioPath];
    *的NSMutableString = trackSection [的NSMutableString stringWithString:boundaryStart];
    [trackSection appendFormat:@内容处置:表格数据;名称= \\跟踪[asset_data] \\;];
    [trackSection appendFormat:@文件名= \\%@ \\\\ r \\ n,[audioPath lastPathComponent]];
    [trackSection appendFormat:@内容类型:应用程序/八位字节流\\ r \\ n \\ r \\ n];    [bodyData appendData:[trackSection dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:trackData];    //结尾
    [bodyData appendData:[boundaryEnd dataUsingEncoding:NSUTF8StringEncoding]];    返回bodyData;
}

I have to upload a mp3 file to SoundCloud, using a HTTP method. I receive no errors, but the file does not appear uploaded on SoundCloud.

I'm using a multipart/form-data request

This is how I'm currently proceeding:(I have already done connection, authorization and I know my user ID).

NSString *url=[NSString stringWithFormat:@"http://api.soundcloud.com/tracks.json?client_id=%@&user_id=%@&title=%@&tag_list=%@&sharing=%@&oauth_token=%@",SOUNDCLOUD_CLIENT_ID, inputData[@"user_id"],inputData[@"title"],inputData[@"tag_list"],inputData[@"sharing"], ACCESS_TOKEN];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
request.HTTPMethod = @"POST";

NSString *boundary= @"SoundCloud";
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\n--%@\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"asset_data\"; filename=\"%@\"\n",@"my file name.mp3"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: audio/mpeg\n\n" dataUsingEncoding:NSUTF8StringEncoding];
NSData *audioData=[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"untitled" ofType:@"mp3"]];
[body appendData:[NSData dataWithData:audioData]];
[body appendData:[[NSString stringWithFormat:@"\n--%@", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

request.HTTPBody = body;

[request setValue:[NSString stringWithFormat:@"%lud",(unsigned long)[body length]] forHTTPHeaderField:@"Content-Length"];
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@,boundary] forHTTPHeaderField:@"content-Type"];
request.timeoutInterval = 30;
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];

The .mp3 file is actually where I search, so that "audioData" has the right content. I receive a 200 HTTP response code:

NSHTTPURLResponse:{ URL: https://api.soundcloud.com/tracks.json?client_id=[...]&user_id=[...]&title=dgd&tag_list=wgn&sharing=public&oauth_token=[...] } { status code: 200, headers {

"Access-Control-Allow-Headers" = "Accept, Authorization, Content-Type, Origin";
"Access-Control-Allow-Methods" = "GET, PUT, POST, DELETE";
"Access-Control-Allow-Origin" = "*";
"Access-Control-Expose-Headers" = Date;
"Cache-Control" = "private, max-age=0, must-revalidate";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=utf-8";
Date = "Mon, 08 Dec 2014 15:58:57 GMT";
Etag = "\"66cc86baea454001c9572594b9caeea0\"";
Server = "am/2";
"Set-Cookie" = "_session_auth_key=\"LdrvaLfDKfaGihR714EaihOotlo=\"";
"Transfer-Encoding" = Identity;
} }

Then, the response json is an array containing the list of all the tracks on my account. No error, but no file is uploaded. The same kind of response is obtained by simulator and device. Any suggestions are welcome.

P.S. I also tried the post request changing the body and the content-type like this, but with no working result:

NSDictionary *body=@{@"asset_data":[[NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"untitled" ofType:@"mp3"]]base64EncodedStringWithOptions:0]};
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
request.HTTPBody = bodyData;
[request addValue:@"application/json" forHTTPHeaderField:@"content-Type"];

解决方案

I now have working code for uploading a song with NSURLRequest. I hope this helps you.

-(void)uploadTrackTitled:(NSString*)title withPath:(NSString*)trackPath {
    NSURLSession* urlSession = [NSURLSession sharedSession];
    NSURLRequest* urlRequest = [self getURLRequest:title withAudioPath:trackPath];

    NSURLSessionDataTask* dataTask = [urlSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@"returned: %ld", (long)httpResponse.statusCode);

        if(data) {
            NSString* stringResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", stringResponse);
        }

        if(error) {
            NSLog(@"%@", [error localizedDescription]);
        }
    }];

    [dataTask resume];
}

-(NSURLRequest*)getURLRequest:(NSString*)title withAudioPath:(NSString*)audioPath {
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    NSString* boundary = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
    CFRelease(uuid);
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.soundcloud.com/tracks"]];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self getPostData:self.scToken withBoundary:boundary andTitle:title withAudioPath:audioPath]];

    NSString* contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];

    return request;
}

-(NSData*)getPostData:(NSString*)token withBoundary:(NSString*)boundary andTitle:(NSString*)title withAudioPath:(NSString*)audioPath {
    NSString* boundaryStart = [NSString stringWithFormat:@"--%@\r\n", boundary];
    NSString* boundaryEnd = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary];
    NSMutableData* bodyData = [[NSMutableData alloc] init];

    //add the token
    NSMutableString* tokenSection = [NSMutableString stringWithString:boundaryStart];
    [tokenSection appendFormat:@"Content-Disposition: form-data; name=\"oauth_token\"\r\n\r\n"];
    [tokenSection appendFormat:@"%@\r\n", token];
    [bodyData appendData:[tokenSection dataUsingEncoding:NSUTF8StringEncoding]];

    //track title
    NSMutableString* titleSection = [NSMutableString stringWithString:boundaryStart];
    [titleSection appendFormat:@"Content-Disposition: form-data; name=\"track[title]\"\r\n\r\n"];
    [titleSection appendFormat:@"%@\r\n", title];
    [bodyData appendData:[titleSection dataUsingEncoding:NSUTF8StringEncoding]];

    //add the audio file
    NSData* trackData = [NSData dataWithContentsOfFile:audioPath];
    NSMutableString* trackSection = [NSMutableString stringWithString:boundaryStart];
    [trackSection appendFormat:@"Content-Disposition: form-data; name=\"track[asset_data]\"; "];
    [trackSection appendFormat:@"filename=\"%@\"\r\n", [audioPath lastPathComponent]];
    [trackSection appendFormat:@"Content-Type: application/octet-stream\r\n\r\n"];

    [bodyData appendData:[trackSection dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:trackData];

    //ending
    [bodyData appendData:[boundaryEnd dataUsingEncoding:NSUTF8StringEncoding]];

    return bodyData;
}

这篇关于使用的SoundCloud API在iOS上载轨道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆