ios - Showing a Download progress UIViewController - objective-c

After implementing the HCDownload for iOS into my app I am successfully able to display the downloading progress of a file.
The problem is that the guy who wrote it, didn't use Xcode to write the module, so even though it should, it does not really work nice when trying to integrate with a project.
These are the main issues I have with it:
If you do a [self.navigationController pushViewController:dlvc animated:YES]; or a [self presentViewController: animated: completion:]; then it shows when it is initiated. I can get out of it, by navigating back, but then when I return to it, it is blank - so I cannot see what the progress is of the download. The download however keeps going, because it appears in my documents folder. ( I use ASIHTTP framework)
Now I am working with storyboard in this project, and because this does not come with a XIB file I thought (which has kinda worked in the past) I could just have a UITableViewController and have this as its Custom Class, but it does not play ball.
Is there a XIB based Download manager FrameWork that someone can point me too, or has anyone had luck with this one?
PS I know Storyboards do not use XIB files, but that way it is easier to integrate into storyboard than no UI files at all:-)
Kind thanks for the tips.
Edit
Here is the code where I implement it:
HCDownloadViewController *dlvc = [[HCDownloadViewController alloc] init];
dlvc.delegate = self;
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
dlvc.downloadDirectory = documentDirectory;
NSString *fileSave = [_streamingURL lastPathComponent];
NSURL *url = [NSURL URLWithString:_streamingURL];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[dlvc downloadURL:url userInfo:nil];
// Add your filename to the directory to create your saved pdf location
NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:fileSave];
NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// Add your filename to the directory to create your temp pdf location
NSString *tempPdfLocation = [cachesDirectory stringByAppendingPathComponent:fileSave];
if (!networkQueue) {
networkQueue = [[ASINetworkQueue alloc] init];
}
failed = NO;
[request setTemporaryFileDownloadPath:tempPdfLocation];
[request setDownloadDestinationPath:pdfLocation];
[request setDownloadProgressDelegate:progressBar];
[request setShowAccurateProgress:YES];

Related

AVPlayer playerWithURL not working after app restart

I am picking a video from the user photo library and than I save the video in the user Documents Folder to be able to play the video even if the user deletes this video from his photo Library. The URL to this file is stored in Core Data.
Everything works fine until the next time I run the App. Somehow it seems like the URL is no longer valid, which is strange because I am able to delete the video file when [AVPlayer playerWithURL:videoURL] fails.
Here is how I pick the video URL:
- (void) imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSURL* videoURL = info[UIImagePickerControllerMediaURL];}
This is how I save the video:
+ (NSURL*) saveVideoInDocumentsFolder:(NSURL*)videoURL name:(NSString*)name {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* pathComponent = [NSString stringWithFormat:#"/%#.%#", name, [videoURL pathExtension]];
NSString* path = [documentsDirectory stringByAppendingPathComponent:pathComponent];
NSError* error = nil;
NSData* videoData = [NSData dataWithContentsOfURL:videoURL options:0 error:&error];
if (error)
return nil;
BOOL success = [videoData writeToFile:path options:NSDataWritingAtomic error:&error];
if (success)
return [NSURL fileURLWithPath:path];
return nil;}
This is how I play the video:
AVPlayer* player = [AVPlayer playerWithURL:videoURL]; // <- AFTER I RESTART THE APP THIS METHOD ALWAYS RETURNS nil!!
AVPlayerViewController* viewController = [[AVPlayerViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
viewController.player = player;
[player play];
Many thanks in advance!
The URL to this file is stored in Core Data
That's the problem. The documents directory URL changes every time you run the app (because you are sandboxed), so it isn't valid the second time. Never never never save an absolute file URL in iOS!
You need to take every time the path directory when close and open app , because when app close it it removes documentDirectory, so you have to take it another time , and if you want to get your video file then save the FILE NAME of that video into preference or Core Data then get documentDirectory path by appending this video name file and you will get your video.
Just have a look: - (code is in swift you can convert it objective c easily)
let fileName = "recording.mp4"
let tempPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let tempDocumentsDirectory: AnyObject = tempPath[0] as AnyObject
let tempDataPath = tempDocumentsDirectory.appendingPathComponent(fileName) as String as String
that FILE NAME you will save in preference or coreData
and when you close and open the app just check do you have FILE NAME save in preference or in core data if yes then take it by appending with documentsDirectory and you will get your video

How do I find the URL of a mp4 resource file?

Why can't I find a resource when it's an ".mp4"?
My code is:
- (IBAction)babelFishButton:(id)sender {
NSURL *url = [[NSBundle mainBundle] URLForResource:#"BabelFish" withExtension:#"mp4"];
MPMoviePlayerController *player =[[MPMoviePlayerController alloc] initWithContentURL: url];
[player prepareToPlay];
[player.view setFrame: self.imageView.bounds]; // player's frame must match parent's
[self.imageView addSubview: player.view];
[player play];
}
BabelFish.mp4 exists in the project navigator, and finder tells me it's in the app root folder, along with main.m, etc.
But the video does not play because url is nil (the file is not being found). I can paste in a copy of the file and rename it "BabelFish.txt", change the extension in the code and it finds the file.
Why won't it find "mp4" files? How do I get the URL of an mp4 file?
Jeff
Try this:
NSString *myUrlSTR = [[NSBundle mainBundle] pathForResource:#"BabelFish" ofType:#"mp4"];
Another thing make sure that your file is not only listed in your Project Explorer, but also included in your Copy Bundle Resources list.

Export image to Instagram - iPhone

I have an image and I want to export it to Instagram, so I can post it.
The code I'm using is:
NSURL *instagramURL = [NSURL URLWithString:#"instagram://location?id=1"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"Image.igo"];
UIImage *image = [UIImage imageNamed:#"01.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
NSURL *imageUrl = [NSURL fileURLWithPath:savedImagePath];
NSLog(#"%#",imageUrl);
UIDocumentInteractionController *docController = [[UIDocumentInteractionController alloc] init];
docController.delegate = self;
docController.UTI = #"com.instagram.exclusivegram";
docController.URL = imageUrl;
//[docController setURL:imageUrl];
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
When I run the app, the App shows the button written "Instagram" its icon, but when I touch it, the button disappear, and nothing happens. The app didn't crash, but nothing happen.
What I missed in my code ?
Regards
Bruno
I guess the problem is you do not retain the UIDocumentInteractionController. Make an ivar for it in your class.
Make sure the method documentInteractionController:didEndSendingToApplication: is called on the delegate.
Also check out the Instagram documentation: http://instagram.com/developer/iphone-hooks/
When triggered, Instagram will immediately present the user with our
filter screen. The image is preloaded and sized appropriately for
Instagram. Other than using the appropriate image format, described
above, our only requirement is that the image is at least 612px tall
and/or wide. For best results, Instagram prefers opening a JPEG that
is 612px by 612px square. If the image is larger, it will be resized
dynamically.
To verify that Instagram is installed check for the URL instagram://app. The URL instagram://location?id=LOCATION_ID is intended for location feeds only!

Displaying images in uiwebview from core data record

So I have an app I've written for the iPad, and I'd like to be able to allow users to insert images into their documents by selecting an image from an album or the camera. All that works great. Because the user might keep the document longer than they keep the image in an album, I make a copy of it, scale it down a bit, and store it in a core data table that is just used for this purpose.
I store the image like this:
NSManagedObjectContext* moc=[(ActionNote3AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSString* imageName=[NSString stringWithFormat:#"img%lf.png",[NSDate timeIntervalSinceReferenceDate]];
Image* anImage = [NSEntityDescription insertNewObjectForEntityForName:#"Image" inManagedObjectContext:moc];
anImage.imageName=imageName;
anImage.imageData=UIImagePNGRepresentation(theImage);
NSError* error=nil;
if(![moc save:&error]) {...
I sub-class NSURLCache, as suggested on Cocoa With Love, and ovverride cachedResponseForRequest thusly:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSString *pathString = [[[request URL] absoluteString]lastPathComponent];
NSData* data = [Image dataForImage:pathString];
if (!data) {
return [super cachedResponseForRequest:request];
}
NSURLResponse *response =[[[NSURLResponse alloc]
initWithURL:[request URL]
MIMEType:[NSString stringWithString:#"image/png"]
expectedContentLength:[data length]
textEncodingName:nil]
autorelease];
NSCachedURLResponse* cachedResponse =[[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease];
return cachedResponse;
}
I also make sure the app uses the sub-classed NSURLCache by doing this in my app delegate in didFinishLaunchingWithOptions:
ANNSUrlCache* uCache=[[ANNSUrlCache alloc]init];
[NSURLCache setSharedURLCache:uCache];
The method that returns the image data from the core data record looks like this:
+(NSData*)dataForImage:(NSString *)name {
NSData* retval=nil;
NSManagedObjectContext* moc=[(ActionNote3AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Image" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"imageName==%#", name];
[request setPredicate:predicate];
NSError* error=nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if ([array count]>0) {
retval=((Image*)[array objectAtIndex:0]).imageData;
}
return retval;
}
To insert the image into the web view, I have an html img tag where the name in src="" relates back to the name in the image table. The point of the NSURLCache code above is to watch for a name we have stored in the image table, intercept it, and send the actual image data for the image requested.
When I run this, I see the image getting requested in my sub-classed NSURLCache object. It is finding the right record, and returning the data as it should. However, I'm still getting the image not found icon in my uiwebview:
So Marcus (below) suggested that I not store the image data in a core data table. So I made changes to accomodate for that:
Storing the image:
NSString* iName=[NSString stringWithFormat:#"img%lf.png",[NSDate timeIntervalSinceReferenceDate]];
NSData* iData=UIImagePNGRepresentation(theImage);
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:iName];
[iData writeToFile:fullPathToFile atomically:NO];
Retrieving the image:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSString *pathString = [[[request URL] absoluteString]lastPathComponent];
NSString* iPath = [Image pathForImage:pathString];
if (!iPath) {
return [super cachedResponseForRequest:request];
}
NSData* idata=[NSData dataWithContentsOfFile:iPath];
NSURLResponse *response =[[[NSURLResponse alloc]
initWithURL:[request URL]
MIMEType:#"image/png"
expectedContentLength:[idata length]
textEncodingName:nil]
autorelease];
NSCachedURLResponse* cachedResponse =[[[NSCachedURLResponse alloc] initWithResponse:response data:idata] autorelease];
return cachedResponse;
}
In debug mode, I see that idata does get loaded with the proper image data.
And I still get the image-not-found image! Obviously, I'm doing something wrong here. I just dont know what it is.
So... What am I doing wrong here? How can I get this to work properly?
Thank you.
I would strongly suggest that you do not store the binary data in Core Data. Storing binary data in Core Data, especially on an iOS device, causes severe performance issues with the cache.
The preferred way would be to store the actual binary data on disk in a file and have a reference to the file stored within Core Data. From there it is a simple matter to change the image url to point at the local file instead.
So it turns out I was way overthinking this. When I write the HTML, I just write the path to the image in with the image tag. Works like a charm.
I would love to know why the solution I posed in my question did not work, though.
And, I did wind up not storing the images in a table.

NSWorkspace lauchApplication weirdness - it only works from within Xcode

#implementation button
- (IBAction)doSomething:(id)pId;
{
NSFileManager *filemgr;
NSString *currentpath;
NSString *appPath;
filemgr = [[NSFileManager alloc] init];
currentpath = [filemgr currentDirectoryPath];
appPath=[currentpath stringByAppendingString:#"/resources/systemRun.app"];
[[NSWorkspace sharedWorkspace] openFile:appPath withApplication:nil];
exit(0);
}
#end
This code works perfectly when I build & run from Xcode, or when I right click the "product" from within Xcode. However when I run the application from the finder it never launches ... Even from within the very build folder.. wtf ?
Don't use currentDirectoryPath to find your resources directory.
NSString *appPath = [[NSBundle currentBundle] pathForResource:#"systemRun" ofType:#"app"];