Playing a video from live stream while also saving the stream to disk on iOS - objective-c

I've been looking into this topic for a while now and I can't really figure out how I could achieve this. Let's say we have a video from an HTTP Stream and I want to be able to play that video in my app, and at the same time the video is also persisted on the disk. I know I can play videos with the AVFoundation or MediaPlayer frameworks and I can load the file/stream via NSURLRequest.
These are two different processes though, which would require loading the video two times. I can't figure out if and how I can combine these two. Is this possible/feasible?

It's Possible. However, for the purpose of your YouTube video if you like I do not want to recommend. becauseof following Youtbe TOS.
For the following reasons:
22.4
We found that your app contains information that may allow its users
to download YouTube content, which is not in compliance with the
YouTube Terms of Service.
"...You shall not download any Content unless you see a "download" or
similar link displayed by YouTube on the Service for that Content. You
shall not copy, reproduce, distribute, transmit, broadcast, display,
sell, license, or otherwise exploit any Content for any other purposes
without the prior written consent of YouTube or the respective
licensors of the Content. YouTube and its licensors reserve all rights
not expressly granted in and to the Service and the Content."
also refer following site question. that's very important. you will definitely need to read.
http://www.iphonedevsdk.com/forum/business-legal-app-store/88260-youtube-downloader.html
Anyway, now I'll tell you about how to implement them.
a. Streaming Service is not difficult to implement. According to Apple's sample code can be easily implemented. Please note the following. this using a AVPlayer. at 3G, Wifi i tested. it' fine. how to test? upload to video your server or get video link. and copy and paste in source code xib textField.
StitchedStreamPlayer
b. Video downloads are available at the same time. I will recommend AFNetworking. ARC support for it. so if apps state is the background, download continue.
AFNetworking
How to Download?
NSURLRequest *request = [NSURLRequest requestWithURL:"your_http_video_url" cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:20];
AFURLConnection *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [[docPaths objectAtIndex:0] stringByAppendingPathComponent:"your_save_video_name.mp4"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setDownloadProgressBlock:^(NSInteger bytesRead, long long
totalBytesRead, long long totalBytesExpectedToRead)
{
//do stuff. about upadte progressbar...
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"downloadComplete"); // show alertView to user.
}];
[operation start];

You should check out this excellent answer:
https://stackoverflow.com/a/23754994/1509392
which explains how this can be done with AVURLAsset and providing data to the resourceLoader object. The idea is that the resourceLoader will ask your delegate for the media data, which you can then download from the source and save to disk.

Related

What is the correct way of sending large file through HTTP POST, without loading the whole file into ram?

I'm currently working on an application for uploading large video files from the iPhone to a webservice through simple http post. As of right now, I build an NSURLRequest and preload all of the video file data before loading the request. This naturally eats a ton of ram if the file is considerably big, in some cases it's not even possible.
So basically my question is: Is there a correct way of streaming the data or loading it in chunks without applying any modifications to the webserver?
Thanks.
EDIT for clarification: I am searching for a way to stream large multipart/form data FROM the iPhone TO a webserver. Not the other way arround.
EDIT after accepting answer: I just found out that apple has some nifty source code written for this exact purpose and it shows appending additional data to the post not just the big file itself. Incase anyone ever needs it: SimpleURLConnections - PostController.m
Yet another EDIT: While using that piece of source code from apple I encountered a very stupid and ugly problem that even wireshark couldn't help me debug. Some webservers don't understand the boundary string when it's declared in between quotes (like in apples example). I had problems with it on Apache Tomcat and removing the quotes worked just wonderful.
You can use NSInputStream on NSMutableURLRequest. For example:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
NSInputStream *stream = [[NSInputStream alloc] initWithFileAtPath:filePath];
[request setHTTPBodyStream:stream];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
}];
You can use a NSInputStream to provide the data to post via -[NSMutableURLRequest setHTTPBodyStream:]. This could be an input stream that reads from a file. You might need to implement the connection:needNewBodyStream: method in your URL connection delegate to provide a new, unopened stream in case the system needs to retransmit the data.
One way to do this is to use an asynchronous NSInputStream in concert with a file. When the asynchronous connection asks you to provide more data, you read in the data from a file. You have a few ways to do this:
UNIX/BSD interface. use open (or fopen), malloc, read, and create a NSData object from the malloced data
use the above with mmap() if you know it
use the Foundation class NSFileHandle APIs to do more or less the same using ObjectiveC
You can read up on streams in the 'Stream Programming Guide'. If this doesn't work for you there are lots of open source projects that can upload files, for instance MKNetworkKit

Uploading From App to Server in IOS

I know that conventionally for an app to interact with the internet, it must use a web service to exchange information. However, how would one upload data(photos, text, audio recordings etc.etc.) from app to server(which holds data for all user accounts)? I know some people use an email-to-server tactic from research but even then it sounds ineffective and slow. How do apps such as Instagram upload so fast? I am trying to replicate that sort of uploading. Please guide me in the right direction.
Thanks for the help!
You should definitely look into AFNetworking. Here is an example of my uploading an image to a php web service:
NSData *imageData = UIImagePNGRepresentation(pageImage);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://www.SERVER.com"]];
//You can add POST parameteres here
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
author, #"author",
title, #"title",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"/PATH/TO/WEBSERVICE.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//This is the image
[formData appendPartWithFileData: imageData name:#"cover_image" fileName:#"temp.png" mimeType:#"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//Setup Upload block to return progress of file upload
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(#"Upload Percentage: %f %%", progress*100);
}];
//Setup Completeion block to return successful or failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(#"response: [%#]",response);
//Code to run after webservice returns success response code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", [operation error]);
//Code to Run if Failed
}];
[operation start];
Edit- Also I use MBProgressHUD to display to the user the uploading on longer uploads.
As you might know, upload speed is always bound to the speed of the connection type you're using. Even the best upload technique will be slow when the connection is slow (GPRS for example, or EDGE, even 3G can be slow if network coverage is not good).
To upload large sets of data faster/better one thing you could do is compressing the data you're sending using ZIP or any other file compression format you wish or even develop you own compression algorithm (you might not want to do that ;-)).
If you want to reduce the overhead of HTTP/HTTPS connections for example, you can write your very own protocol for data exchange, implement it on the client/server side and upload faster. This will be a lot of work as you have to do all the implementation work not only for the protocol itself as you need to add security etc. But even if you choose to create a protocol, as said in the beginning, it will be slow if the connection is slow.
Update: A presenatation by Mike Krieger (Co-Founder of Instagram) where he covers your question just crossed my way https://speakerdeck.com/u/mikeyk/p/secrets-to-lightning-fast-mobile-design?slide=1.
The reason why you think it's so fast is, that they're updating the UI before the request (the Upload in this case) even completes. This is what Mike describes as "being optimistic". If the request fails you can still notify the user, but in the meantime make him feel productive and act like the request completed successfully.
This is a pretty open ended question but here are a few things to look at:
"Uploading fast" depends on the user's connection and server bandwidth so I won't get into that.
You can upload photos (and other files) by creating NSData objects and attaching them to a POST request. There is already a ton of sample code for uploading NSData but to convert a UIImage you will do the following:
NSData *imageData = UIImagePNGRepresentation(image);
You can do this using the built in Cocoa classes (NSMutableURLRequest) and with 3rd party networking classes (such as AFNetworking - just scroll down to file uploads).
When I send simple data to my webserver, I use the following approach: Use the ASIHttpRequest framework for connecting to your sever. Send the data in HTTP Post body, which is easy to do in the ASIHttpRequest framework. You will want to convert your data to either XML or JSON(use the SBJson framework for this) before sending it. I then write php scripts that parse the json or xml and then input this data into my database with custom SQL scripts. I can give you code snippets if you need them for any of these procedures...
It seems to me that, with your first sentence, you've basically answered your own question.
You need something on your server to receive the files and then you write client code to match. It could be as simple as ftp or as complex as a custom protocol depending on the security and control that you need.

Why is NSData crashing my app?

I have a url that is a link to an audio file and will be played using AVFoundation.framework. But for some reason, when the app reaches setting the NSData it crashes. Please help.
NSURL *url = [NSURL URLWithString:songPathForm];
NSData *soundData = [NSData dataWithContentsOfURL:url];
EDIT::::
This is what I did to make it stop crashing, but the data contains nothing
NSString *url = [songPathForm stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSURL *url = [NSURL URLWithString:songPathForm];
NSURLRequest *songRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
NSURLConnection *songConnection = [[NSURLConnection alloc] initWithRequest:songRequest delegate:self];
if(songConnection)
{
songData = [[NSMutableData data] retain];
}
It comes out as <>
There is absolutely no way to answer this question as it is worded, but here are some clues:
if there is a crash, there is a backtrace. Post it.
if there is a crash, there is some kind of an error. Post it.
Given that code, there are two failure modes that I can think of:
songPathForm is nil or corrupt and/or not an URL.
the data at the URL is too large to download and causes the app to attempt to allocate a HUGE amount of memory (there are cases where an allocation can be large enough to crash an app w/o the system jetsam mechanism kicking in).
There is no crash message, it just freezes and stops responding. url
is not nil it is...
Then why did you say your app crashed?!
dataWithContentsOfURL: is synchronously downloading the contents of whatever is at the URL.
Thus, you are blocking the main event loop during the download and that is why your app is not responsive.
You need to asynchronously download the data; i.e. not block the main event loop.
However that probably won't entirely fix your problem as it looks like the contents of that URL is really large and, thus, you are likely going to run out of memory if you try to download in memory.
You either need to download the file to the disk or you need to download only parts of it that you need right now or you need to stream it (if it really is a large audio file as the URL implies).
The code in your updated question doesn't make any sense. How do you expect songData to be filled with data from the connection?
When doing stuff asynchronously, you are basically saying "go do this stuff and let me know every now and then how it is going". In this case, that'd be a notification that more data is available or that the connection is done reading (or in error).
You can't ask for the data immediately because the data isn't immediately available.
You'll want to read through this guide.

Fastest way to retrieve a folder's content on Mac, in obj-c

Well, the title is quite explicit, but a little explantations for those interested in the background.
I'm developing a little image browser. On part of the application is a directory browser which allows me to browse all the folders of my hard drive and mounted volumes.
And while profiling, I noticed that the most time consuming method of my application was the following piece of code :
// get the content of the directory
NSFileManager * fileManager = [NSFileManager defaultManager];
NSURL * url = [NSURL fileURLWithPath:mPath];
mCachedContent = [[fileManager contentsOfDirectoryAtURL:url
includingPropertiesForKeys:nil
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil] retain];
// parse the content, count the number of images and directories.
for (NSURL * item in mCachedContent)
{
if (CFURLHasDirectoryPath((CFURLRef)item))
{
++mNumChildren;
}
else if ([FileUtils isImage:[item path]] == YES)
{
++mNumImages;
}
}
This is necessary so that the NSOutlineView can know if a directory is expandable (and the number of images is also a feature I need)
To be more precise, the most time consuming method if [NSFileManager contentsOfDirectoryAtURL...]
So, is there any other way of getting a directory's content more efficient than the one I'm using ?
Thanks in advance for any help !
No matter how you write this function (e.g. with either Cocoa's NSFileManager API or the Unix opendir(3)/readdir(3) API), it's going to be I/O-bound—you're going to spend more time waiting on I/O than on any CPU operations performed in the middle layers.
If this is truly your bottleneck, then that means you're doing way too much I/O. Make sure you're not doing anything stupid like continually reading the contents of the same directory over and over again hundreds of times per second. If you need to continually watch a particular directory and take action whenever something in that directory changes (e.g. a file gets written to, a file is created or deleted, etc.), then use the File Systems Events API. This allows you to efficiently respond to those events when they happen without having to continually poll the directory.

Download an save an image file on HDD with Cocoa

I'm building a program, and I'm quite confident using Objective-C, but I don't know how to programmatically download a file from the web and copy it on the hard drive.
I started with :
NSString url = #"http://spiritofpolo.com/images/logo.png";
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
But then I don't know what to do with the data... that sucks, no ;)
Can somebody help?
You're close; the last thing you need is a call to -[NSData writeToFile:atomically:].
While that approach, with the final step provided by fbrereto, will work, it does not handle failure gracefully (indeed, it does not handle any sort of failure at all) and will block your application for the duration of the download.
Use NSURLDownload instead. It requires more code, but broken network connections, cut-off downloads, and inaccessible destination paths will not (necessarily) silently break your app.