iPhone App Crashes When trying to play video - xcode

I'm trying to get a simple view based app to play a video, but it crashes, heres my code,
- (IBAction)playButton:(id)sender {
NSString *stringPath = [[NSBundle mainBundle] pathForResource:#"1" ofType:#"mov"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
mpc = [[MPMoviePlayerController alloc]initWithContentURL:url];
[mpc setMovieSourceType:MPMovieSourceTypeFile];
[[self view]addSubview:mpc.view];
[mpc setFullscreen:YES];
[mpc play];
}
#end
and here is where it takes me in xcode when it fails
//
// main.m
// video_play
//
// Created by nathaniel harman on 20/04/2013.
// Copyright (c) 2013 machupicchumobile. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "VideoPlayAppDelegate.h"
int main(int argc, char *argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([VideoPlayAppDelegate class]));
}
}

try like this ,
NSString *audio=[[NSBundle mainBundle]pathForResource:#"1" ofType:#"mov"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:audio];

Try this like, where you will find the code I'm using for playing the movie or video.
http://kiranjasvanee.wordpress.com/2013/09/19/play-video-or-movie-in-iphone/?preview=true&preview_id=3&preview_nonce=cf5d01de8d
Let me implement this code here, so can review it,
First you have to import the MediaPlayer header library to use it’s MPMoviePlayer for playing any movie or video.
You can import this library in .h or .m view controller – depends upon where you declaring your MPMoviePlayerViewController object.
Library import:-
#import MediaPlayer/MediaPlayer.h
Object declaration:-
MPMoviePlayerViewController *moviePlayer;
implement this below code in .m file, when play movie pressed:-
below used Movie_URL identifier contains the URL of video or movie.
- (IBAction)BtnVideoShowCalled:(id)sender
{
// Put your Navigation and Tabbar related code here.
Ex :- /* self.navigationController.navigationBarHidden=YES; */
//If you wanna play a video from tableview, then assign tag to _btn and add target this function to that _btn. Ex :-
/*
//Where, record is a object of Messages class.
NSInteger tid = [sender tag];
*/
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"%#",Movie_URL]];
if(URL)
{
Class mplayerControllerClass = NSClassFromString(#"MPMoviePlayerViewController");
if(mplayerControllerClass != nil) {
moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:URL];
moviePlayer.wantsFullScreenLayout = YES;
[moviePlayer shouldAutorotateToInterfaceOrientation:YES];
if(moviePlayer)
{
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
}
[movieplayer readyPlayer];
}
}
}

Related

MacOS Mojave UNNotificationAttachment thumbnail not showing up in notifications

This is the (simplified) code I am trying to run. The image file exists and the app does not crash. What happens in that the image is deleted from the location as mentioned in the documentation for UserNotifications. However, the image thumbnail does not show up in the notification that is generated.
I am not sure what else I am missing here.
#import <UserNotifications/UserNotifications.h>
int main(int argc, const char * argv[]) {
UNUserNotificationCenter* notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
[notificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {}
];
UNMutableNotificationContent *localNotification = [UNMutableNotificationContent new];
localNotification.title = [NSString localizedUserNotificationStringForKey:#"Title" arguments:nil];
localNotification.body = [NSString localizedUserNotificationStringForKey:#"Body Text" arguments:nil];
localNotification.sound = [UNNotificationSound defaultSound];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)lastObject];
NSString *testUrl = [path stringByAppendingPathComponent:#"imageFile.jpg"];
NSURL* url = [NSURL fileURLWithPath:testUrl];
CGRect rect = CGRectMake(0.25, 0.25, 0.75, 0.75);
NSDictionary* options = # {
#"UNNotificationAttachmentOptionsTypeHintKey": (__bridge NSString*) kUTTypeJPEG,
#"UNNotificationOptionsThumbnailHiddenKey" : #NO,
#"UNNotificationAttachmentOptionsThumbnailClippingRectKey": [NSValue valueWithRect: rect]
};
UNNotificationAttachment* imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:#""
URL:url
options:options
error:nil];
localNotification.attachments=#[imageAttachment];
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:#"Identifier" content: localNotification trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
NSLog(#"Notification created");
}];
[NSThread sleepForTimeInterval:100.0f];
return 0;
}
Check if you set up the key NSUserNotificationAlertStyle
Check the system response((BOOL granted, NSError * _Nullable error)) if you get an error, please provide it.
Add notification in the completion block.
Do not run your code in main, app might haven't been properly initialized, use AppDelegate appDidFinishLaunching instead.
Test with triggerWithTimeInterval:[NSDate date].timeIntervalSince1970+30 (it contradicts documentation but works in my case)
Collapse you app in delivery time, it might be not delivered when app is in focus.
Also go to "System Preferences" and check if your app is allowed to post notifications.(If you do not manage to find your app in the list, please, let us know, it might be the key to the problem)

macOS 10.13: "Scheduling the NSURLDownload loader is no longer supported."

Running my macOS app in macOS 10.13, I see printed to the console:
Scheduling the NSURLDownload loader is no longer supported.
What does this mean?
The Sparkle Updater seems to be the culprit in the instances I have found. I guess the Sparkle dev team will be on to it and hopefully we'll no longer see the message after Sparkle is updated.
It appears to mean You have just created an instance of the deprecated class NSURLDownload.
To show this, create a new Cocoa command-line tool project in Xcode and replace the code in main.m with the following:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSURL* url = [[NSURL alloc] initWithString:#"https://example.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0];
NSLog(#"Will print strange sentence to console") ;
[[NSURLDownload alloc] initWithRequest:request
delegate:nil];
NSLog(#"Did print strange sentence to console") ;
}
return 0;
}
Build and run. I get the following result in console (timestamps removed):
Will print strange sentence to console:
Scheduling the NSURLDownload loader is no longer supported.
Did print strange sentence to console
I would say the "fix" is to replace the deprecated NSURLDownload with NSURLSession.
You can correct it directly in the source code for Sparkle. Update SUAppcast.m file at line 82 by replace the NSURLDownload with the following:
NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL *location, __unused NSURLResponse *response, NSError *error) {
if (location) {
NSString *destinationFilename = NSTemporaryDirectory();
if (destinationFilename) {
// The file will not persist if not moved, Sparkle will remove it later.
destinationFilename = [destinationFilename stringByAppendingPathComponent:#"Appcast.xml"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *anError = nil;
NSString *fromPath = [location path];
if ([fileManager fileExistsAtPath:destinationFilename])
[fileManager removeItemAtPath:destinationFilename error:&anError];
BOOL fileCopied = [fileManager moveItemAtPath:fromPath toPath:destinationFilename error:&anError];
if (fileCopied == NO) {
[self reportError:anError];
} else {
self.downloadFilename = destinationFilename;
dispatch_async(dispatch_get_main_queue(), ^{
[self downloadDidFinish:[[NSURLDownload alloc] init]];
});
}
}
} else {
[self reportError:error];
}
}];
[downloadTask resume];

iOS 8 app extension get image from safari

Im using app extension share on my app,
is working fine for giving me back the url and "message" for the sharing,
but my image appear as nil when logged
#interface ShareViewController ()
#property (nonatomic, strong)__block NSString *urlString;
#property (nonatomic, strong)__block UIImage *photo;
#property (nonatomic, strong)NSString *msg;
#end
#implementation ShareViewController
- (BOOL)isContentValid {
// Do validation of contentText and/or NSExtensionContext attachments here
return YES;
}
- (void)viewDidLoad{
[super viewDidLoad];
//Get msg
NSExtensionContext *myExtensionContext = [self extensionContext];
NSArray *inputItems = [myExtensionContext inputItems];
for(NSExtensionItem* item in inputItems){
self.msg = [NSString stringWithFormat:#"%#", [item.attributedContentText string]];
}
// get url
NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
NSItemProvider *itemProvider = item.attachments.firstObject;
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeURL]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error) {
self.urlString = [NSString stringWithFormat:#"%#",url.absoluteString];
}];
}
//img
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeImage options:nil completionHandler:^(UIImage *image, NSError *error) {
self.photo = image;
}];
}
}
- (void)didSelectPost {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
NSLog(#"big fat fella");
NSLog(#"msg: %#", self.msg);
NSLog(#"url %#:", self.urlString);
NSLog(#"im %#:", self.photo);
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
[self.extensionContext completeRequestReturningItems:#[] completionHandler:nil];
}
so please note im getting url and message on didSelectPost, but image shows as null,
how to get image?
thx!
To get the image automatically generated on the share extension while sharing on Safari, use loadPreviewImageWithOptions:completionHandler:previewImageHandler.
[itemProvider loadPreviewImageWithOptions:nil completionHandler:^(UIImage *image, NSError *error){
if(image){
//do anything here with the image
}
}
I'm able to retrieve the thumbnail auto-generated while sharing on Safari, but I'm unable to change the size of the image using:
NSString * const NSItemProviderPreferredImageSizeKey;
Reference: https://developer.apple.com/documentation/foundation/nsitemprovider

On Snow Leopard, why is -[<ABImageClient> consumeImageData:forTag:] not being called after [ABPerson beginLoadingImageDataForClient:] is called?

I'm trying to load image date for person entries in the shared ABAddressBook. In particular, I'm calling
-[ABPerson beginLoadingImageDataForClient:]
and passing as the argument an object which adopts ABImageClient and implements
-[<ABPersonClient> consumeImageData:forTag:]
The approach I'm using works fine on Mountain Lion, but fails on Snow Leopard. In particular, -consumeImageData:forTag: never gets called.
The following sample command line program demonstrates my approach:
#import <Foundation/Foundation.h>
#import <AddressBook/AddressBook.h>
#interface ImageConsumer : NSObject <ABImageClient>
#property (nonatomic, strong) NSMutableDictionary *imagesForNumbers;
#end
#implementation ImageConsumer
- (id)init
{
self = [super init];
if (self) {
self.imagesForNumbers = [NSMutableDictionary dictionary];
}
return self;
}
- (void)consumeImageData:(NSData *)data forTag:(NSInteger)tag
{
[self.imagesForNumbers setObject:data forKey:[NSNumber numberWithInteger:tag]];
NSLog(#"%s: loaded data of length %zu for tag %zd", __PRETTY_FUNCTION__, data.length, tag);
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSArray *persons = [[ABAddressBook sharedAddressBook] people];
ImageConsumer *imageConsumer = [[ImageConsumer alloc] init];
for (ABPerson *person in persons) {
NSInteger loadingKey = [person beginLoadingImageDataForClient:imageConsumer];
NSLog(#"requested data person named %# %# and received tag %zd", [person valueForProperty:kABFirstNameProperty], [person valueForProperty:kABLastNameProperty], loadingKey);
}
[[NSRunLoop mainRunLoop] run];
}
return 0;
}
Am I misusing the ABAddressBook calls for loading image data for instances of ABPerson? Is this a bug with ABAddressBook on Snow Leopard? If so, is there a work-around?

Saving a PDF file through a UIWebView so that is visible (in the same WebView) even offline

I have this question that is driving me crazy: could I save a PDF file (that is online) locally on an iOS Device so that I can view the file every time even offline in the same UIWebView?
If I could, how?
If you have control over such UIWebView and the URL it opens, then yes, you can. See the following code as example. It uses the ASIHttpRequest library, which you can find at http://allseeing-i.com/ASIHTTPRequest/
#import "WebViewPDFViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "ASIHTTPRequest.h"
#implementation WebViewPDFViewController
-(NSString *) md5:(NSString *) str {
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5( cStr, strlen(cStr), result );
return [NSString stringWithFormat:
#"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
-(void) viewWillAppear:(BOOL)animated {
NSString *pdfOnlinePath = #"http://redinter.eu/web/files/revistas/2Dummy.pdf";
// Check if the file is already stored locally. If it is not, then first
// download it, and load from the local cache. Next requests will always
// load from the local cache
NSString *pdfHash = [self md5:pdfOnlinePath];
NSString *pdfCachePath = [NSString stringWithFormat:#"%#/pdfcache_%#.pdf",
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0],
pdfHash];
if ([[NSFileManager defaultManager] fileExistsAtPath:pdfCachePath]) {
NSLog(#"Cached file found, using it");
}
else {
// Not found in the local cache, download and store it
NSLog(#"File not found in the local cache, going to download it");
ASIHTTPRequest *downloadRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:pdfOnlinePath]];
[downloadRequest setDownloadDestinationPath:pdfCachePath];
[downloadRequest startSynchronous];
}
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfCachePath]];
UIWebView *webView = [[[UIWebView alloc] initWithFrame:self.view.bounds] autorelease];
[webView loadRequest:request];
[self.view addSubview:webView];
}
- (void)dealloc {
[super dealloc];
}
#end
I have tested it here ant it works fine.

Resources