Thumbnail for youtube video - iphone

I am trying to create a thumbnail for youtube video,but me getting below error:-
Error Domain=AVFoundationErrorDomain Code=-11850 "Operation Stopped" UserInfo=0xa07ac00 NSLocalizedDescription=Operation Stopped, NSUnderlyingError=0xa07e580 "The operation couldn’t be completed. (OSStatus error -12939.)", NSLocalizedFailureReason=The server is not correctly configured.
Please help me out to create a thumbnail of youtube video from youtube link.
The Code am using to create thumbnail is as follows:-
NSURL *url = [NSURL URLWithString:strVideoURL];
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
{
if (result != AVAssetImageGeneratorSucceeded) {
NSLog(#"couldn't generate thumbnail, error:%#", error);
}
// TODO Do something with the image
NSLog(#"CGImage---- %#", im);
UIImage *thumbnail=[UIImage imageWithCGImage:im];
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(30, 50, 120, 120)];
imageView.backgroundColor=[UIColor redColor];
imageView.image=thumbnail;
[image addSubview:imageView];
UIView *view=(UIView*)[self.view viewWithTag:10];
[view removeFromSuperview];
};
CGSize maxSize = CGSizeMake(128, 128);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];

Although your question doesn't have any source code of yours so i have no idea where have you gone wrong. Try this, its working for me.
#define YOUTUBE_URL #"https://gdata.youtube.com/feeds/api/videos?v=2&author=%#&orderby=published"
NSString *userName = #"ipl";
_url = [NSURL URLWithString:[NSString stringWithFormat:YOUTUBE_URL,userName]];
-(void) fetchYoutubeThumbnails {
NSURLRequest *_request = [[NSURLRequest alloc] initWithURL: _url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[recievedData appendData:data]; //recievedData is a class variable of type NSMutableData
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *xmlString = [[NSString alloc] initWithData:recievedData encoding:NSUTF8StringEncoding];
NSDictionary *result = [XMLReader dictionaryForXMLString:xmlString error:Nil];
if(result.count > 0) {
NSMutableArray *items = [[result objectForKey:#"feed"] objectForKey:#"entry"];
for(int i = items.count -1; i >= 0; i--) {
NSDictionary *item = [items objectAtIndex:i];
NSString *videoThumbnaulUrl = [[[[item valueForKey:#"media:group"] valueForKey:#"media:thumbnail"] objectAtIndex:0] valueForKey:#"url"];
// Use this url to get the thumbnail.
}
}

Related

Download Multiple images using Native functionality IOS

How to download multiple images and save it to the disk.
The Send request i'm using is below.
for(NSDictionary *image in [data objectForKey:#"Catalogues"])
{
NSString *imurl =[image objectForKey:#"Image_Path"];
NSLog(#"%#",imurl);
NSString *urlstring =imurl;
NSLog(#"demo %#",urlstring);
NSURL *mailurl =[NSURL URLWithString:urlstring];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:mailurl];
NSOperationQueue *ques =[[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:ques completionHandler:^(NSURLResponse *respo, NSData *data, NSError *err) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 150, 150)];
im.image = image;
[self.view addSubview:im];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",documentsDirectory]
any native methods available for multiple images?
you can implement an AsyncImage class like this
in AsyncImage.h file
#import <UIKit/UIKit.h>
#interface AsyncImage : UIView
{
NSURLConnection* connection;
NSMutableData* data;
UIImageView *image;
UIActivityIndicatorView *scrollingWheel;
NSString *imgName;
}
-(void)loadImageFromString:(NSString*)url;
-(void)loadImageFromURL:(NSURL*)url;
-(void)setLocalImage:(UIImage *)localImage;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
#end
in AsyncImage.m file
#import "AsyncImage.h"
#implementation AsyncImage
-(id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
[self addSubview:scrollingWheel];
self.clipsToBounds = YES;
}
return self;
}
-(void)loadImageFromString:(NSString*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
imgName = [[[url componentsSeparatedByString:#"/"] lastObject]retain];
// NSLog(#"imgName=%#",imgName);
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
// NSLog(#"imagePath=%#",imagePath);
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)setLocalImage:(UIImage *)localImage
{
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
image = [[[UIImageView alloc] initWithImage:localImage] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
}
//for URL
-(void)loadImageFromURL:(NSURL*)url
{
[scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
NSString *strurl=[NSString stringWithFormat:#"%#",url];
imgName = [[[strurl componentsSeparatedByString:#"/"] lastObject]retain];
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:imagePath] == NO)
{
NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
} else {
UIImage *img = [[UIImage alloc]initWithContentsOfFile:imagePath];
image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[scrollingWheel stopAnimating];
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj
{
[data appendData:dataObj];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[connection release];
connection=nil;
NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
[data writeToFile:imagePath atomically:YES];
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
image.frame = self.bounds;
[self addSubview:image];
[data release];
data=nil;
[scrollingWheel stopAnimating];
}
-(void)dealloc
{
[scrollingWheel release];
[super dealloc];
}
-(NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection
{
if (connection !=nil) {
[connection cancel];
connection=nil;
}
if(data!=nil){
[data release];
data=nil;
}
[scrollingWheel stopAnimating];
}
#end
and at your viewController.m you can import this class and call it like this
AsyncImage *imgBOD = [[AsyncImage alloc] initWithFrame:CGRectMake(10, 46, 70, 70)];
[imgBOD loadImageFromString:[dictData objectForKey:#"image_path"]];
[self.view addSubview:imgBOD];
There is no "native method" for this particular problem.
If you just want to save a list of images to disk, you can improve your approach by not creating UIImages in the first place, just treat the data as binary data and save to disk directly.
In order to maintain low memory foot-print, implement NSURLConnection's delegate methods, and write (append) the image data piece-wise to the destination file as the chunk data arrives in connection:didReceiveData:.
The latter will be best solved by creating a dedicated class which encapsulates NSURLConnection and other related states and is subclassed from NSOperation and employs the asynchronous style implementing NSURLConnection delegates.
You might consider a third party library, too. A warning though: almost all well-known third party network libraries will not let you easily write data in pieces to a file. Per default, they accumulate all received data into one NSMutableData object. That may increase your memory-foot print, since images may be large, and since you can start multiple connections at once.
Also, don't start more than two connections at once.

iPhone - NSURLConnection asynchronous download using URLs in NSArray

I have seen almost all the posts about NSURL on this site, and I am still stuck. I am using Xcode 4.5.
I am trying to download images and display them in a UIScrollView.
I want to download asynchronously download images using URLs, that get stored in an array populated using JSON. I get the URLs from a JSON grab off of my database. That works quite well and I can see the URL's being placed into the urlArray, but making the URLConnection to get the image, seems to fail.
I can't get any of the images to download, or at least they don't show up in my imageArray.
Here is my code and thank you for any help!! Let me know what else is needed
- (void)viewDidLoad
{
[super viewDidLoad];
//show network activity to user.... very useful
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//call getJSON. getJSON does not parse, but it connects and gets the data.
[self getJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getJSON
{
NSURL *url = [NSURL URLWithString:#"http://"My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//just initialize the connection, do not
[[NSURLConnection alloc] initWithRequest:request delegate:self]; //"Ecression result unused" warning here
}
- (void)getNextImage
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
imageData = [UIImage imageWithData:imgData];
[imageArray addObject:imageData];
}
NSLog(#"LEAVING getNextImage");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
theJsonData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[theJsonData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
jsonArray = [NSJSONSerialization JSONObjectWithData:theJsonData options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self getNextImage];
//display the images..... Not sure why this is in connectionDidFinishLoading.
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageData];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
NSLog(#"!!!!!!leaving connection did finnish loading!!!!!");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//show error message to user if there is a connection error.
UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"The Download could not complete - please make sure you're connected to the internet." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
//turn off the network activity indicatior
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
you never download imageData. you assign it the request object . thats why you get the warning too. a NSURLConnection object is not a NSData object: NSData *imgData = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self]; //"Incompatible pointer types initializing ..." warning here
I would today rewrite it using the startAsyncConnection method. sec
-- there you go, untested and written in text edit but it should get you started (I reused most of your code but cut it down a lot too)
#import "RootViewController.h"
#interface RootViewController ()
#property(assign) IBOutlet UIScrollView *mainScroll;
#end
#implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self getJSONAndImageData];
}
- (void)getJSONAndImageData
{
NSURL *url = [NSURL URLWithString:#"http://My server goes here/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse*r, NSData*d, NSError*e) {
[self parseJSONAndGetImages:d];
}];
}
- (void)parseJSONAndGetImages:(NSData*)data
{
NSMutableArray *urlArray = [[NSMutableArray alloc] init];
//This is where all the JSON Parsing is being done.
//Turn off the data indicator, because the download is complete.
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *jsonArray = (NSArray*)[NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; //"Incompatible pointer types initializing ..." warning here => likely not an array then
assert([jsonArray isKindOfClass:[NSArray class]]);
//could be made in one liner with KVC
//get the URL strings out of the jsonArray
for (int x = 0; x < jsonArray.count; x++)
{
NSString *urlString = [[jsonArray objectAtIndex:x] objectForKey:#"image_URL"];
NSLog(#"String is %# ", urlString);
[urlArray addObject:urlString];
}
[self loadImageArray:urlArray handler:^(NSArray* imageArray) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
for (int x = 0; x < imageArray.count; x++)
{
CGRect frame;
frame.origin.x = self.mainScroll.frame.size.width * x;
frame.origin.y = 0;
frame.size = self.mainScroll.frame.size;
UIImageView *nextIV = [[UIImageView alloc] initWithFrame:frame];
[nextIV setImage:imageArray[x]];
[self.mainScroll addSubview:nextIV];
//NSLog(#"Pass %d", x);
}
self.mainScroll.contentSize = CGSizeMake(self.mainScroll.frame.size.width * imageArray.count,1.0);
}];
}
//for SIMPLICITY I do synchronous networking here!
- (void)loadImageArray:(NSArray *)urlArray handler:(void(^)())handler {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSMutableArray *imageArray = [NSMutableArray array];
for (int y = 0; y < urlArray.count; y++)
{
NSString *urlString = [urlArray objectAtIndex:y];
NSLog(#"Array String is: %# ", urlString);
NSURL *arrayURL = [NSURL URLWithString:urlString];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:arrayURL];
NSData *imgData = [NSURLConnection sendSynchronousRequest:imageRequest returningResponse:nil error:nil];
UIImage *image = [UIImage imageWithData:imgData];
[imageArray addObject:image];
}
dispatch_async(dispatch_get_main_queue(),^ {
handler(imageArray);
});
});
}
#end

How to monitor pdf download process in iphone sdk

In my application i need to download pdf file from url.i know how to download pdf file from url and store in local document directory.But i need to show downloading process and i want to know whether download is completed.Please any body give an idea..
Here My code:
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.msy.com.au/Parts/PARTS.pdf"]];
//Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
Use ASIHTTPRequest for download file. for below code I had used ASIHTTPRequest
float currentProgress;
UILabel *dwnLbl;
UIProgressView * myProgressIndicator;
UIProgressView *progressBar;
#property (nonatomic, retain) ASIHTTPRequest *rqstForAudio;
-(void)viewDidLoad{
self.av=[[UIAlertView alloc] initWithTitle:#"Downloading.." message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[self.actV setFrame:CGRectMake(125, 60, 37, 37)];
dwnLbl = [[UILabel alloc] initWithFrame:CGRectMake(45, 30, 200, 37)];
dwnLbl.textAlignment = UITextAlignmentCenter;
dwnLbl.font = [UIFont boldSystemFontOfSize:20];
dwnLbl.backgroundColor = [UIColor clearColor];
dwnLbl.textColor = [UIColor whiteColor];
progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[progressBar setFrame:CGRectMake(45, 65, 200, 20)];
progressBar.progress = 0;
[self.av addSubview:dwnLbl];
[self.av addSubview:progressBar];
}
-(void)downLoadBook{
NSString *strAudioURL=#"http://www.msy.com.au/Parts/PARTS.pdf"
// check first locally exists or not
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#/%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],
AudioFolder];
NSDictionary *dOfAudios=[NSDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios valueForKey:strAudioURL]) {
} else {
self.av.title = #"Downloading..";
[self.av show];
NSString *pdf = #"bookTitle.pdf";
NSURL *audioURL = [NSURL URLWithString:strAudioURL];
NSString *strPathToDownload=[NSString stringWithFormat:#"%#/%#",[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0],pdf];
[self.rqstForAudio setDownloadProgressDelegate:myProgressIndicator];
if(!self.rqstForAudio || [self.rqstForAudio isFinished]) {
self.rqstForAudio=[ASIHTTPRequest requestWithURL:audioURL];
[self.rqstForAudio setDelegate:self];
[self.rqstForAudio setDownloadProgressDelegate:self];
[self.rqstForAudio setAllowResumeForFileDownloads:YES];
[self.rqstForAudio setCachePolicy:ASIUseDefaultCachePolicy];
[self.rqstForAudio setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[self.rqstForAudio setDidFailSelector:#selector(failedToLoad:)];
[self.rqstForAudio setDidFinishSelector:#selector(finishedLoading:)];
[self.rqstForAudio setDownloadCache:[ASIDownloadCache sharedCache]];
[self.rqstForAudio setDownloadDestinationPath:strPathToDownload];
[self.rqstForAudio startAsynchronous];
}
}
}
- (void)failedToLoad:(ASIHTTPRequest*)request {
[self.av dismissWithClickedButtonIndex:0 animated:YES];
NSLog(#"failed to download");
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"MESSAGE" message:#"Failed to Download" delegate:self cancelButtonTitle:RETRY otherButtonTitles:nil, nil];
av.delegate = self;
[av show];
}
- (void)finishedLoading:(ASIHTTPRequest*)request {
NSLog(#"finished loading");
NSString *strPathToAudioCache=[NSString stringWithFormat:#"%#",
[(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
NSMutableDictionary *dOfAudios=[NSMutableDictionary dictionaryWithContentsOfFile:strPathToAudioCache];
if([dOfAudios allKeys].count>0) {
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
} else {
dOfAudios=[NSMutableDictionary dictionary];
[dOfAudios setValue:[request downloadDestinationPath] forKey:[[request url] description]];
}
[self.av dismissWithClickedButtonIndex:0 animated:YES];
[dOfAudios writeToFile:strPathToAudioCache atomically:YES];
}
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes{
[self setProgress:[myProgressIndicator progress]];
}
- (void)setProgress:(float)progress
{
currentProgress = progress;
if (!progress == 0.0) {
}
if(currentProgress*100 == 100.00){
self.av.title = #"Finishing..";
}
progressBar.progress = currentProgress;
dwnLbl.text = [NSString stringWithFormat:#"%.2f%%",currentProgress*100];
}
EDIT
You can used the NSURLSession method to implement such scenario
NSURLSession
I'd highly recommend taking a look at ASIHTTPRequest for easy file downloading.
where the numbers of the functionality thru you can able to use the download progress.

MPMoviePlayerController with no content (iOS 5) - The Operation Could Not Be Completed

I have problem with MPMoviePlayerController (self.mp). When I want to access duration property, I get 0, when I want to access thumbnail…, I get nil. On iOS 4 it is OK, iOS 5 it is not.
After all app says to me: The Operation Could Not Be Completed.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
if([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]){
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
double hashToNameOfFile = [NSDate timeIntervalSinceReferenceDate] * 1000.0;
NSString *finalPath = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"%.0f.%#", hashToNameOfFile, #"MOV"]];
NSString *finalPathToThumbRetina = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f#2x.%#", hashToNameOfFile, #"jpg"]];
NSString *finalPathToThumb = [rootPath stringByAppendingPathComponent:[NSString stringWithFormat: #"thumb_%.0f.%#", hashToNameOfFile, #"jpg"]];
// we do need retina now, we use real name for CoreData
NSString *finalImage = [finalPath lastPathComponent];
NSString *finalImageThumb = [finalPathToThumb lastPathComponent];
if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(tempFilePath)){
// Copy it to the camera roll.
UISaveVideoAtPathToSavedPhotosAlbum(tempFilePath, self, #selector(video:didFinishSavingWithError:contextInfo:), tempFilePath);
}
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
// create thumbnail of video
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
NSData *videoData2 = [NSData dataWithContentsOfFile:finalPath];
NSLog(#"LENGTH %i", [videoData2 length]);
NSLog(#"FINAL PATH %#", finalPath);
UIImage *image = [[[UIImage alloc] init] autorelease];
image = [self.mp thumbnailImageAtTime:(NSTimeInterval)1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
NSLog(#"%#", [image size]);
UIImage *thumbImageRetina = [image thumbnailImage:400 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
UIImage *thumbImage = [image thumbnailImage:200 transparentBorder:0 cornerRadius:0 interpolationQuality:kCGInterpolationDefault];
NSData *thumbImageRetinaData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImageRetina, 1.0)];
NSData *thumbImageData = [NSData dataWithData:UIImageJPEGRepresentation(thumbImage, 1.0)];
if ( [thumbImageRetinaData writeToFile:finalPathToThumbRetina atomically:YES] ) {
NSLog(#"RETINA THUMB SAVED");
}
else{
NSLog(#"RETINA THUMB NOT SAVED");
}
if ( [thumbImageData writeToFile:finalPathToThumb atomically:YES] ) {
NSLog(#"THUMB SAVED");
}
else{
NSLog(#"THUMB NOT SAVED");
}
// duration of video
double dur = [self.mp duration];
NSLog(#"DUR %f", dur);
TaleRecords *newTaleRecord = (TaleRecords *)[NSEntityDescription insertNewObjectForEntityForName:#"TaleRecords" inManagedObjectContext:_context];
newTaleRecord.content = finalImage;
newTaleRecord.date = [NSDate date];
NSDecimalNumber *latNum = [[NSDecimalNumber alloc] initWithDouble:[self.latitude doubleValue]];
NSDecimalNumber *longNum = [[NSDecimalNumber alloc] initWithDouble:[self.longitude doubleValue]];
newTaleRecord.latitude = latNum; // vertical
newTaleRecord.longitude = longNum; // horizontal
[latNum release];
[longNum release];
newTaleRecord.contentType = [[NSString alloc] initWithFormat:#"cTypeVideo"];
newTaleRecord.thumb = finalImageThumb;
newTaleRecord.duration = [NSNumber numberWithDouble:dur];
newTaleRecord.tale = tales;
tales.record = [newTaleRecord tale].record;
NSError *error = nil;
if (![_context save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
[CLController.locationManager stopUpdatingLocation];
[self dismissModalViewControllerAnimated:YES];
}
More simple example
I am doing this:
// save video to application directory
NSData *videoData = [NSData dataWithContentsOfFile:tempFilePath];
if ( [videoData writeToFile:finalPath atomically:YES] ) {
NSLog(#"SAVED");
}
else{
NSLog(#"NOT SAVED");
}
At tempFilePath is real video content and I write it to finalPath. After that I create MPMoviePlayerController instance:
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:finalPath]];
self.mp = moviePlayer;
[moviePlayer release];
But self.mp give me no content. When I want to do [self.mp duration], it returns zero/nil. Path to resource works, but it seems no content is there.
Thank you for your help.
I figured out my problem.
It is like iOS5 is not comfortable with:
NSString *tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
so instead, if you just use
NSURL *someUrl =[info objectForKey:UIImagePickerControllerMediaURL] ;
and then initial mpmovieplayercontroller with this url, it works fine for me,
which is exactly the opposite of iOS4.
here is my code:
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
mediaURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSLog(#"%#",mediaURL);
if (!mymoviePlayer) {
mymoviePlayer=[[MPMoviePlayerController alloc]initWithContentURL:mediaURL];
[mymoviePlayer setControlStyle:MPMovieControlStyleNone];
[mymoviePlayer.view setFrame: videoView.bounds];
[videoView addSubview:mymoviePlayer.view];
}
else
{
[mymoviePlayer setContentURL:mediaURL];
[mymoviePlayer stop];
[mymoviePlayer setInitialPlaybackTime:-1];
}
[self dismissModalViewControllerAnimated:YES];
}

Displaying an Image from URL Objective C

Is there any way of achieving the following that avoids using "initWithData" ? (Just in case you are curious, initWithData is getting my app flagged by Apple as using an illegal API sigh).
NSData * imageData = [NSData dataWithContentsOfURL : [NSURL URLWithString : [details image]]];
picture = [[UIImage alloc] initWithData:imageData];
Many thanks,
Martin
if you want to get the image data,then initialize a UIImage using that data:
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://Serverurl/pic007.jpg"]];
cell.image = [UIImage imageWithData: imageData];
[imageData release];
First of all, you should do this asynchronously so that your thread won't block. Here is the code for the class:
#implementation AsyncImageView
+ (void)initialize {
[NSURLCache setSharedURLCache:[[SDURLCache alloc] initWithMemoryCapacity:0
diskCapacity:10*1024*1024
diskPath:[SDURLCache defaultCachePath]]];
}
- (void)setImageFromURL:(NSURL *)url{
/* Put activity indicator */
if(!activityIndicator) {
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect frame = [activityIndicator frame];
frame.origin.x = (self.frame.size.width - frame.size.width)/2;
frame.origin.y = (self.frame.size.height - frame.size.height)/2;
activityIndicator.tag = 9999;
activityIndicator.frame = frame;
[self addSubview:activityIndicator];
[activityIndicator startAnimating];
}
/* Cancel previous request */
if(fetchImageConnection) {
[fetchImageConnection cancel];
}
[imageData release];
/* Start new request */
NSURLRequest *req = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
imageData = [NSMutableData new];
fetchImageConnection = [NSURLConnection connectionWithRequest:req
delegate:self];
[fetchImageConnection retain];
}
- (void)setImageFromDisk:(UIImage *)img {
self.image = img;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[imageData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(connection == fetchImageConnection) {
self.image = [UIImage imageWithData:imageData];
[[NSNotificationCenter defaultCenter] postNotificationName:#"imageDownloaded" object:self];
[activityIndicator removeFromSuperview];
[imageData release];
[activityIndicator release];
activityIndicator = nil;
imageData = nil;
fetchImageConnection = nil;
}
[connection release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
NSLog(#"error: %#", error);
}
#end
Try this code:
NSString *imgString = #"https://www.lockated.com/system/attachfiles/documents/000/002/489/original/ZPMHaJUSjAGnUrVuOmbqoExRMryvcySVOIkJQMivnAntvpmpYd.jpg?1501833649";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgString]];
accountImageView.image = [UIImage imageWithData: imageData]; // accountImageView is imageView
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://Serverurl/pic007.jpg"]];
self.image=nil;
UIImage *img = [[UIImage alloc] initWithData:receivedData ];
self.image = img;
[img release];
I hope this code will help you!!