我想通知我的用户有关上传某些Mpeg 3文件的进度。只有一个。 但正如我在标题中所说的那样,我遇到了问题。
我的上传代码在这里
- (NSString *) upload: (NSData*) postData {
NSString *str;
NSURL *url = [NSURL URLWithString:@"http://example.com/test.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
request.HTTPMethod = @"POST";
NSString *boundary = @"unique-consistent-string";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// add mp3 data
if (postData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=audio\r\n", @"audioFormKey"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: audio/mpeg3\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:postData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength2 = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength2 forHTTPHeaderField:@"Content-Length"];
NSLog(postLength2);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if(data.length > 0)
{
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(str);
}
}];
return str;
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
NSLog(@"bytes transfer %li" ,(long)bytesWritten);
}
这里永远不会调用Log“bytes transfer”。
非常感谢您的支持
答案 0 :(得分:0)
在完成处理程序中调用sendAsynchronousRequest:
然后调用sendSynchronousRequest:
有点奇怪吗?
在任何情况下,您都没有将URL连接配置为具有委托,因此永远不会调用您的委托方法。
您需要分配并实例化URLConnection,然后将其配置为使用您的对象作为委托。它需要符合NSURLConnectionDelegate
协议。