2

HTTP 프로토콜로 비디오 스트리밍 서비스를 구현해야합니다. url을 MPMoviePlayerController에 설정하는 방법과 headerField를 NSMutableURLRequest로 설정하는 방법을 알고 있지만 어떻게 조합해야하는지 잘 모릅니다. 아래의 코드를 구현하지만 작동하지 않습니다. 바이너리 데이터에 파일 정보가 없기 때문에 가정합니다.헤더 정보를 MPMoviePlayerController URL에 삽입하는 방법은 무엇입니까?

- (void) openUrl 
{ 
    NSMutableURLRequest *reqURL = [NSMutableURLRequest requestWithURL: 
           [NSURL URLWithString:@"http://111.222.33.44/MOV/2013/4/123123123"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; 

    [reqURL setHTTPMethod:@"GET"]; 
    [reqURL setValue:@"Mozilla/4.0 (compatible;)" forHTTPHeaderField:@"User-Agent"]; 
    [reqURL setValue:@"AAA-bb" forHTTPHeaderField:@"Auth-Token"]; 
    [reqURL setValue:@"bytes=0-1024" forHTTPHeaderField:@"Range"]; 
    [reqURL setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    [NSURLConnection connectionWithRequest:reqURL delegate:self]; 

} 


- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{  
    NSLog(@"Received"); 
    NSError * jsonERR = nil; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myMove.ts"]; 

    [data writeToFile:path atomically:YES]; 
    NSLog(@"copied"); 
    NSURL *moveUrl = [NSURL fileURLWithPath:path]; 

    MPMoviePlayerController *player = [[MPMoviePlayerController alloc]init]; 
    [player setContentURL:moveUrl]; 
    player.view.frame = self.view.bounds; 
    player.controlStyle = MPMovieControlStyleEmbedded; 
    [self.view addSubview:player.view]; 
    [player play]; 
} 

대리자 메서드에 데이터가 있지만 작업 방법을 잘 모르겠습니다. 누군가 제게 어떻게하는지 알려주세요. 인증 토큰 및 범위는 필수 매개 변수입니다.

감사합니다.

답변

1

돌아가서 NSURLConnection 및 URL 로딩 시스템에 대한 설명서를 읽어보십시오. -connection:didReceiveData:은 파일의 각 청크가 도착할 때마다 두 번 이상 호출됩니다. 한 번에 전체 데이터 만 도착한다고 가정하기보다는이를 처리해야합니다.

+0

그런데 어떻게 처리할까요? – z33

7

애플이 MPMoviePlayerController의 요청에 헤더를 삽입하는 쉬운 방법을 공개하지 않는다는 것은 사실입니다. 약간의 노력으로 사용자 정의 NSURLProtocol을 사용하여이를 수행 할 수 있습니다. 자, 해보자!

MyCustomURLProtocol.h :

@interface MyCustomURLProtocol : NSURLProtocol <NSURLConnectionDelegate, NSURLConnectionDataDelegate> 

@property (nonatomic, strong) NSURLConnection* connection; 

@end 

MyCustomURLProtocol.m : 당신은 사용자 정의 URL 프로토콜을 사용하기 전에

@implementation MyCustomURLProtocol 

// Define which protocols you want to handle 
// In this case, I'm only handling "customProtocol" manually 
// Everything else, (http, https, ftp, etc) is handled by the system 
+ (BOOL) canInitWithRequest:(NSURLRequest *)request { 
    NSURL* theURL = request.URL; 
    NSString* scheme = theURL.scheme; 
    if([scheme isEqualToString:@"customProtocol"]) { 
     return YES; 
    } 
    return NO; 
} 

// You could modify the request here, but I'm doing my legwork in startLoading 
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { 
    return request; 
} 

// I'm not doing any custom cache work 
+ (BOOL) requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b { 
    return [super requestIsCacheEquivalent:a toRequest:b]; 
} 

// This is where I inject my header 
// I take the handled request, add a header, and turn it back into http 
// Then I fire it off 
- (void) startLoading { 
    NSMutableURLRequest* mutableRequest = [self.request mutableCopy]; 
    [mutableRequest setValue:@"customHeaderValue" forHTTPHeaderField:@"customHeaderField"]; 

    NSURL* newUrl = [[NSURL alloc] initWithScheme:@"http" host:[mutableRequest.URL host] path:[mutableRequest.URL path]]; 
    [mutableRequest setURL:newUrl]; 

    self.connection = [NSURLConnection connectionWithRequest:mutableRequest delegate:self]; 
} 

- (void) stopLoading { 
    [self.connection cancel]; 
} 

// Below are boilerplate delegate implementations 
// They are responsible for letting our client (the MPMovePlayerController) what happened 

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    [self.client URLProtocol:self didFailWithError:error]; 
    self.connection = nil; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.client URLProtocol:self didLoadData:data]; 
} 

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 
} 

- (void) connectionDidFinishLoading:(NSURLConnection *)connection { 
    [self.client URLProtocolDidFinishLoading:self]; 
    self.connection = nil; 
} 

@end 

, 당신을 등록해야합니다. 당신의 AppDelegate.m에서 :

#import "MyCustomURLProtocol.h" 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

    // ... Your normal setup ... 

    [NSURLProtocol registerClass:[MyCustomURLProtocol class]]; 

    return YES; 
} 

마지막으로, 당신은 사용자에게 MPMediaPlayerController와 사용자 정의 URL 프로토콜이 필요합니다.

NSString* theURLString = [NSString stringWithFormat:@"customProtocol://%@%@", [_url host],[_url path]]; 
_player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:theURLString]]; 

MPMoviePlayerController 지금 customProtocol:// 대신 정상 http://로 요청을 시도합니다. 이 설정을 사용하여 요청을 가로 채고 헤더를 추가하고 http로 변환 한 다음 모든 것을 시작합니다.

+0

슬프게도 이것은 시뮬레이터에서만 장치에서 작동하지 않습니다. iOS 9 –

관련 문제