Different behaviour of [NSMutableString writeToFile] in iOS7 and iOS8 - file

Here i have demo code for saving NSMutableString in to File (FileName.dat)
NSError* error = nil;
NSMutableString* dat = [[NSMutableString alloc] initWithCapacity:1];
BOOL result = [dat writeToFile:#"FileName.dat" atomically:YES encoding:NSUTF8StringEncoding error:&error];
but i have two different output while rung it in iOS7 and iOS8beta5
Output XCode5+iOS7
Output XCode5+iOS8
While running it in iOS7 it shows that there in an error in parsing file path,
but in iOS8beta5 it crash by saying that [NSFileManager fileSystemRepresentationWithPath:] have nil or empty path.
Question :
In both SDK iOS8 and iOS7 it take NSError as argument to return error, so i believe that it should return error instead of crashing application
Is apple mansion any changes regarding it, If yes then please give me reference link for the same.

The path you pass to [NSData writeToFile:atomically:] is not complete and should be a full path.
That is normally done by getting the path to the Documents folder and appending that filename.

The problem is your filename, #"FileName.dat", there is no path to the directory to save to. NSFileManager does not do this itself, you'll want to save to the Documents folder normally. Here is the code I usually use:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:myFileName];

Related

Must we have to download the remote file before using AirDrop?

I am sending the remote file (for example: image file, pdf file ... ) to Airdrop.
I have only the direct link of this file : http://example.com/xxx/png.
Currently, I am doing something like below code
NSString *filePath = self downloadFileFromServerWithURL
NSURL *urlFilePath = [NSURL fileURLWithPath:filePath];
NSArray *Items = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:indexPath.row],
urlFilePath,nil];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:Items applicationActivities:[NSArray arrayWithObjects:xxx, yyy,nil];
[self presentViewController:activityViewController animated:YES completion:nil];
So, my question is, how can I share the remote file with Airdrop without downloading it before?
I show a lot of iOS softwares can do that, like DropBox
Thank you
you should look into using a subclass of UIActivityItemProvider which will let you asynchronously get/generate the actual item to be shared. The AirDrop sample code has an example of this.

Why won't any other video file format work except .mov?

I have an app on the app store which plays a selection of videos. Currently all of the videos are in the .mov file format but this makes the size of the app rather large so i'm trying to use a different file format to reduce the overall size of the app.
I am trying to use the mp4 format as this is reducing the size of each video by more than a half but when I do, the app crashes when I try to play the video with the following error message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSURL initFileURLWithPath:]: nil string parameter
I have used the following code for each video in my implementation file and changed the file name and type to match the new video so I don't understand why there should be a problem with the file path.
- (IBAction)playDaresWins:(id)sender {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"DaresWins" ofType:#"mov"]];
_moviePlayer =
[[MPMoviePlayerController alloc]
initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:_moviePlayer];
_moviePlayer.controlStyle = MPMovieControlStyleNone;
_moviePlayer.shouldAutoplay = YES;
[self.view addSubview:_moviePlayer.view];
[_moviePlayer setFullscreen:YES animated:NO];
}
Am I missing something?
.mov isn't a video format or codec, it's a container. The developer documentation provides a list of supported video codecs, bit rates, and resolution (link here - I won't post them here as they can change from OS version to OS version).
However, I don't think that's the problem, because it looks as if you're getting an exception when you're creating the NSURL, not when you're playing the video. That suggests that the path you're providing for your video doesn't exist. Are you sure you have a) the right filename, b) the right extension (perhaps it's MP4 instead of MOV), or c) have added the movie file into your project correctly?

Attach object using iOS6 UIActivityViewController

I'm migrating to use the UIActivityViewController for sharing in iOS6, but I can't figure out how to create email attachment objects to be included when sharing by email.
The corresponding code in iOS5 is:
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
[picker addAttachmentData:data mimeType:#"application/XXX" fileName:fileName];
You have very limited control over UIActivityViewController, but if you're attaching well-know mime types, I found you can get it to work correctly by providing the associated file extension in a file URL. For example, if your attachment is a vCard, use the ".vcf" extension in the file URL:
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// The file extension is important so that some mime magic happens!
NSString *filePath = [docsPath stringByAppendingPathComponent:#"vcard.vcf"];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
[data writeToURL:fileUrl atomically:YES]; // save the file
// Now pass the file URL in the activity items array
UIActivityViewController *avc = [[UIActivityViewController alloc] initWithActivityItems:
#[#"Here's an attached vCard", fileUrl] applicationActivities:nil];
[vc presentModalViewController:avc animated:YES];
For anyone wondering why their files aren't being shared using UIActivityViewController to apps like DropBox and other generic file handling applications, what you really want is a UIDocumentInteractionController.
Use it something like this:
class ViewController {
var openInController:UIDocumentInteractionController!
init() {
openInController = UIDocumentInteractionController(URL: docURL)
}
func shareDoc {
openInController.presentOptionsMenuFromRect(CGRectZero, inView: self.view, animated: true)
}
}
From what I can tell you can't do this with the UIActivityViewController -- I can't even manage to make it present HTML content for the message body -- so you may be better off using SLComposeViewController.

OpenCV cvHaarDetectObject error

I am making a project in Visual Studio 2010 using Qt4.8.0 and OpenCV2.3.1 library. Everything is fine as long as I don't use
cvHaarDetectObjects()
function. The program was compiled and built without problems, but when I try to run the application the error 0xc000007b appears. I've done similar program in win console and this function work properly. Why am I receiving this error message? I also try to use:
CascadeClassifier *haar;
haar->load("haarcascade_frontalface_alt.xml");
but it doesn't work even in console.
Example code
MainWindow.cpp:
MainWindow::MainWindow()
{
temp = cvCreateImage(cvSize(200, 200), 8, 1);
haarface = (CvHaarClassifierCascade*) cvLoad("haarcascade_frontalface_alt.xml");
storage = cvCreateMemStorage(0);
twarze = cvHaarDetectObjects(temp, haarface, storage, 1.1, 3, CV_HAAR_DO_CANNY_PRUNING, cvSize(100,100));
}
MainWindow.h:
class MainWindow
{
private:
CvMemStorage *pamiec;
CvHaarClassifierCascade * haarface;
IplImage *temp2;
CvSeq *twarze;
public:
MainWindow(void);
};
Maybe it something wrong with .xml files?
Are you sure the file haarcascade_frontalface_alt.xml exists in the current directory?
If it does not exist, then cvLoad will return NULL. Use full path for the xml file.
Also, what is error 0xc000007b? Could you post the full error description?
I simply changed slashes to backslashes and it works ;) cvLoad("\haarcascades\haarcascade_frontalface_alt.xml");
EDITED: ok, it doesn't crashes. Actually I am working with 2.4.8 edition o opencv. The problem with this code is cvHaarDetectObjects that seems to be not longer supported. It is recomended to use detectMultiScale instead.

How do I get files in my own file format to have its own dynamic icon?

Our application has a file format similar to the OpenDocument file format (see http://en.wikipedia.org/wiki/OpenDocument) - i.e. zipped with a manifest file, a thumbnail image, etc.
I notice that OpenOffice files have a preview image of the Open Office file as their icons, both in Windows and in Linux. Is there some way to accomplish this for our files: i.e. I want a dynamic icon based on the internal thumbnail.png?
Edit 1 Wow, thanks for all the quick answers. Thumbnailer looks great for the GNOME world. Windows I'll be looking into those links, thanks. As for the comment question: programmatically OR via our installer.
Edit 2 Oh, forgot Mac. How about on the Mac? (Sorry Mac lovers!) Also are there any links or info for how OpenOffice does their IconHandler stuff - since ours would be very similar?
Windows
What you need is an Icon Handler, also known as a Thumbnail Handler. Here is an example written as an active x control.
Another resource is to look up Property Handlers, which should also point to you to the latest and greatest way of having dynamic meta data handled correctly in windows.
These are dynamic solutions - they aren't needed if you just want an icon associated with all your files - they are only used when you want windows explorer to display an icon based on what's in the file, not just the extension, and when the file changes the icon is updated to reflect the changes. It doesn't have to be an image of the file itself, either, the thumbnail handler can generate any image based on the file contents.
The property handler updates other metadata, such as song or video length, so you can use all the metadata Windows Explorer supports.
Regarding MAC support, this page says, "The Mac and Windows operating systems have different methods of enabling this type of thumbnail, and in the case of the Mac OS, this support has been inconsistent from version to version so it hasn't been pursued [for Adobe InDesign]."
OS X
Icons for Mac OSX are determined by the Launch Services Database. However, it refers to a static icon file for all files handled by a registered application (it's not based on extension - each file has meta data attached that determines the application to which it belongs, although extensions give hints when the meta data doesn't exist, such as getting the file from a different OS or file system)
It appears that the dynamic icon functionality in OSX is provided by Finder, but searches aren't bringing up any easy pointers in this direction. Since Finder keeps changing over time, I can see why this target is hard to hit...
Gnome
For Gnome you use a thumbnailer. (thanks Dorward)
This is an extraordinarily simple program you write, which has 3 command line arguments:
input file name, the file you are describing with the thumbnail (or URI if you accept those instead)
output file name, where you need to write the PNG
size, a number, in pixels, that describes the maximum square image size you should produce (128 --> 128x128 or smaller)
I wish all systems were this simple. On the other hand this doesn't support animation and a few other features that are provided by more difficult to implement plugins on other systems.
KDE
I'm a bit uncertain, but there are a few pointers that should get you started. First is that Konqueror is the file manager and displays the icons - it supports dynamic icons for some inbuilt types, but I don't know if these are hardcoded, or plugins you can write. Check out the Embedded Components Tutorial for a starting point.
There's a new (ish?) feature (or planned feature...) called Plasma which has a great deal to do with icons and icon functionality. Check out this announcment and this initial implementation.
You may need to dig into the source of Konqueror and check out how they did this for text files and others already implemented.
-Adam
Mac OSX since version 10.5 …
… has two approaches:
Your document is in the standard OSX bundle format and has a static image
This can be done by creating a subfolder QuickLook and placing the Thumbnail/Preview.png/tiff/jpg inside.
Everything else needs a QuickLook generator plugin which can be stored in either /Library/QuickLook ~/Library/QuickLook or inside the YourApp.app/Contents/Library/QuickLook Folders.
This generator is being used to create Thumbnails and QuickLook previews on the fly. XCode offers a template for this. The template generates the needed ANSI C files which have to be implemented. If you want to write Object-C code you have to rename the GenerateThumbnailForURL.c and GeneratePreviewForURL.c to GenerateThumbnailForURL.m and GeneratePreviewForURL.m (and read the Apple Devel Docs carefully ;) )
Simple zip container based demo:
You will have to add the Cocoa.framework and Foundation.framework to your project
In your GenerateThumbnailForURL.c (this is partly out of my head - so no guarantee that it works out of the box ;) ):
#include <Cocoa/Cocoa.h>
#include <Foundation/Foundation.h>
OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* unzip the thumbnail and put it into an NSData object */
// Create temporary path and writing handle for extraction
NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingFormat: [NSString stringWithFormat: #"%.0f.%#" , [NSDate timeIntervalSinceReferenceDate] * 1000.0, #"png"]];
[[NSFileManager defaultManager] createFileAtPath: tmpPath contents: [NSData alloc] attributes:nil];
NSFileHandle *writingHandle = [NSFileHandle fileHandleForWritingAtPath: tmpPath];
// Use task to unzip - create command: /usr/bin/unzip -p <pathToFile> <fileToExtract>
NSTask *unzipTask = [[NSTask alloc] init];
[unzipTask setLaunchPath: #"/usr/bin/unzip"];
// -p -> output to StandardOut, added File to extract, nil to terminate Array
[unzipTask setArguments: [NSArray arrayWithObjects: #"-p", [(NSURL *) url path], #"Thumbnails/thumbnail.png", nil]];
// redirect standardOut to writingHandle
[unzipTask setStandardOutput: writingHandle];
// Unzip - run task
[unzipTask launch];
[unzipTask waitUntilExit];
// Read Image Data and remove File
NSData *thumbnailData = [NSData dataWithContentsOfFile: tmpPath];
[[NSFileManager defaultManager] removeFileAtPath: tmpPath handler:nil];
if ( thumbnailData == nil || [thumbnailData length] == 0 ) {
// Nothing Found. Don't care.
[pool release];
return noErr;
}
// That is the Size our image should have - create a dictionary too
CGSize size = CGSizeMake(256, 256);
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:size.width],kQLPreviewPropertyWidthKey,
[NSNumber numberWithInt:size.height],kQLPreviewPropertyHeightKey,
nil];
// Get CGContext for Thumbnail
CGContextRef CGContext = QLThumbnailRequestCreateContext(thumbnail, size, TRUE, (CFDictionaryRef)properties);
if(CGContext) {
NSGraphicsContext* context = [NSGraphicsContext graphicsContextWithGraphicsPort:(void *)CGContext flipped:size.width > size.height];
if(context) {
//These two lines of code are just good safe programming…
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
NSBitmapImageRep *thumbnailBitmap = [NSBitmapImageRep imageRepWithData:thumbnailData];
[thumbnailBitmap draw];
//This line sets the context back to what it was when we're done
[NSGraphicsContext restoreGraphicsState];
}
// When we are done with our drawing code QLThumbnailRequestFlushContext() is called to flush the context
QLThumbnailRequestFlushContext(thumbnail, CGContext);
// Release the CGContext
CFRelease(CGContext);
}
[pool release];
return noErr;
}
Info.plist
You will have to modify your info.plist file too - when you open it up it has a lot of fields pre-set. Most of them are self-explaning (or will not have to be changed) but I had to add the following structure (copy paste should do - copy the text, go into the plist editor and just paste.):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>com.pkware.zip-archive</string>
</array>
<key>UTTypeDescription</key>
<string>i-net Crystal-Clear Report File</string>
<key>UTTypeIconName</key>
<string>generic</string>
<key>UTTypeIdentifier</key>
<string>com.company.product</string>
<key>UTTypeReferenceURL</key>
<string>http://your-url.com</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>$fileEXT$</string>
</array>
</dict>
</dict>
</array>
</plist>
This will register your filetype $fileExt$ and tell the system that your filetype is a zipy format type. A nice refference, that I used here is the QuickLook IPA Plugin from googlecode
In Windows, what you need is to implement an Icon Handler. I did this many moons ago and it is not difficult as long as you know the basics of COM.
See: http://msdn.microsoft.com/en-us/library/bb776857(VS.85).aspx
For Gnome you use a thumbnailer.
for WINDOWS try this:
http://www.easydesksoftware.com/news/news12.htm
Executables have the icon inside the file (potentially multiple) as a "resource".
Data files pick up an icon based on file association.
If you want a custom icon per file that is much harder. you either need too fool the OS into thinking it is an executable and embed the icon as a resource in the file, or deep link into the OS to override the default icon selection routine.
I think, "custom own" icon can have only PE files in windows. Every other icons for file extensions are stored in windows registry.
For specification of PE file, you can look at An In-Depth Look into the Win32 Portable Executable File Format and Peering Inside the PE: A Tour of the Win32 Portable Executable File Format.
How it works in other OS, I don't know :/.
I don't know about Linux, but for Windows you can start here:
http://msdn.microsoft.com/en-us/library/bb774614.aspx
Edit: I think this interface is for the thumbnails shown in thumbnail view, not icons. Sorry for wasting your time.

Resources