How i retrieve data in iOS xCode SDK? - titanium

I am using Titanium. and I want to make Titanium Module (for iOS).
every thing is working fine. But, how i retrieve data in xCode whose i send through .js file.
in .js file
var data = "Mritunjay";
var oldData = "Singh";
var data = module_tset.findData({"newData":data,"oldData":oldData});
in xCode
-(id)findData:(NSMutableArray *)args
{
NSMutableArray *ary = [[NSMutableArray alloc]initWithArray:args];
// How i retrieve "newData" Value in xCode?
}
please help me..! thanks

First you should check the documentation for this.
Also, check the example moddevguide projects on GitHub, they have very simple and straightforward examples of how to do this.
In a nutshell heres the code to extract those arguments (assuming you setup this correctly).
-(id)findData:(id)args
{
ENSURE_SINGLE_ARG(args,NSDictionary); // Standard practice
NSString *newData_Pass = [TiUtils stringValue:[args objectForKey:#"newData"]];
// Now do something with newData!
}
Thats it!

Related

Zip/Rar files with SWIFT

I am new to SWIFT and I just started implementing my first application for OS X. I created a simple project and decided Ill look into different frameworks for using zip/rar files. I started with ZipArchive as recommended but couldn't make it work in my project - didn't even compile (probably something wrong with my setup), I had similar experience with Objective-Zip and SSZipArchive. Finally I stumbled on the framework zip zap which attached to my project perfectly.
I looked into the examples:
ZZArchive* oldArchive = [ZZArchive archiveWithURL:[NSURL fileURLWithPath:#"/tmp/old.zip"] error:nil];
ZZArchiveEntry* firstArchiveEntry = oldArchive.entries[0];
NSLog(#"The first entry's uncompressed size is %lu bytes.", (unsigned long)firstArchiveEntry.uncompressedSize);
NSLog(#"The first entry's data is: %#.", [firstArchiveEntry newDataWithError:nil]);
but I couldn't make it work with SWIFT. The problem I faced is that I couldn't create a NSURL that worked with the ZZArchive.
let zip:ZZArchive = ZZArchive(NSURL(fileURLWithPath:"/Users/../tesData/test.zip"))
led to
fatal error: unexpectedly found nil while unwrapping an Optional value
and everything else I tried either didn't compile with a unwrapping error or compiled but on execution led to this error.
Can someone please either help me solve my unzipping problem, or lead me to a solution of how to zip/unzip/read zip/rar/cbr files with swift.
This should fix it
var path = NSURL.fileURLWithPath("/Users/../tesData/test.zip")
var archive: ZZArchive = ZZArchive(URL:(fileURLWithPath:path!), error: &err)
Here is an implementation of zzzip in swift
//Declare
var err: NSError? = NSError()
var path = NSURL.fileURLWithPath("/PathToZipFile/file.zip")
var URL3 = NSURL.fileURLWithPath("/pathanywhereinsystemtosaveunzipedfolder/")
var URL2 = NSURL.fileURLWithPath("/PathToUnzippedFile/file.xxx")
var fileManager = NSFileManager.defaultManager() //1
let archive: ZZArchive = ZZArchive(URL:(fileURLWithPath:path!), error: &err)//2-3
//Create Folder
fileManager.createDirectoryAtURL(URL3!, withIntermediateDirectories: true, attributes: nil, error: &err)
//Write First entry of archive to file
var k = archive.entries[0].newDataWithError(nil)
k.writeToURL(URL2!, atomically: false)
This works for small text files and images. it does have its limitations due to no errorchecking and only writing the first archive entery to a file. If any paths are wrong you will end with errors as soon as you try and compile.

"defaults read com.apple.dock" as Objective C method

I try to read the plist / xml file which is behind the terminal commando:
defaults read com.apple.dock
I tried NSUserDefaults without success. Maybe you can help me. Thanks.
You can use CFPreferences, for example
CFStringRef orient = (CFStringRef) CFPreferencesCopyAppValue( CFSTR("orientation"), CFSTR("com.apple.dock") );
Boolean hidesIsValid = false;
Boolean hides = CFPreferencesGetAppBooleanValue( CFSTR("autohide"), CFSTR("com.apple.dock"), &hidesIsValid );
While JWWalker's answer that uses CoreFoundation APIs works fine, a more modern way is to use Foundation APIs, like so:
if let defaults = UserDefaults(suiteName: "com.apple.dock") {
let orientation = defaults.string(forKey: "orientation")
let autohide = defaults.bool(forKey: "autohide")
...
}

Phonegap Plugins

I need some Help regarding Phonegap plugins:
First , i have a JS File which invoke the native code using the phonegap.exec() containing the result handler function, error handler function , a reference to the native class's name and native function name as well as an array of parameters . My question is : if it is possible to invoke the function (native method) with given specified parameters?
That means : in my phonegap plugin file (.h & .m)
1- can i specify the arguments and their Types (NSInteger, NSString) like java
void myMethod(int a , string b){}
-(void) myMethod:(NSMutableArray )arguments withDict:(NSMutableDictionary)options;
Or is it as specified by Phonegap or Objective C ?
2- And what does it withDict means in this case ??
3- can i addicate this?
4- Why should my Code looks like this ?
-(void)myMethod: (NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
NSString *callbackID =[arguments pop];
NSString *myParam = #"";
NSArray *arrayArguments = [[arguments objectAtIndex:0] componentsSeparatedByString:#"|"];
NSString *stringArgument = ([arArguments objectAtIndex:0]);
I want to invoke my method like this :
why shall i put my arguments (as a String array element) then take it out , split it to get the right element from the String )?
Many Thanks for helping
Ok here's how you do it… The example I've added in below is a implementation of the Email plugin in Phonegap, with multiple strings. You can always substitute my string code to identify NSNumbers, or any other kind of arguments.
In JS ::
First I create the arguments with their values. . .
var attachmentData = {};
attachmentData.data = userData;
attachmentData.fileName = fileName;
var mailData = {};
mailData.toRecipients = "";
mailData.subject = "Exporting Backup for user data";
mailData.body = "User data for application. Please find the attachment containing the data from the last week.";
nativeMail(attachmentData, mailData);
Now we call a function that packages all this data for a Phonegap Plugin and sends it to the plugin class
function nativeMail(attachmentData, mailData){
e_args = {};
if(mailData.toRecipients)
e_args.toRecipients = mailData.toRecipients;
if(mailData.subject)
e_args.subject = mailData.subject; //"Hello World";
if(mailData.body)
e_args.body = mailData.body;
//call to phonegap plugin for native mail iOS
e_args.attachmentFileName = attachmentData.fileName;
e_args.datatoattach = attachmentData.data;
cordova.exec(null, fail, "EmailComposer", "showEmailComposer", [e_args]);
}
Now the EmailComposer.h file
- (void) showEmailComposer:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
And finally, how to take these arguments from the Mutablle Dictionary/Array and retrieve our string values.
- (void) showEmailComposer:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString* toRecipientsString = [options valueForKey:#"toRecipients"];
NSString* ccRecipientsString = [options valueForKey:#"ccRecipients"];
NSString* bccRecipientsString = [options valueForKey:#"bccRecipients"];
NSString* subject = [options valueForKey:#"subject"];
NSString* body = [options valueForKey:#"body"];
NSString* isHTML = [options valueForKey:#"bIsHTML"];
. . . . . .
}
This is the only way to go about it. Its to do with the way that Phonegap itself handles data to be passed from your javascript web app to the native class. It cannot be changed. The MutableDictionary or the MutableArray will handle any kind of data you need it to. There are no limitations. However, the passing of this data can only be done using the format above. Once you have the options and arguments in the .m class, you are free to retrieve them or parse them into the data type you need.

Core Data and unique UIImage per object

I am making a simple app where the user can create severals objects which are saved with CoreData.
My problem is, I want each object to have an image linked to it. The image is brought by the iphone camera or the user personal Camera roll, so the images will have a pretty high weight (> 1MB each I think).
I read that when the weight of images is that high, the good way to handle this is to save the images in the documentsDirectory folder, and save the path to coreData. I achieved this pretty easily.
But how do I find a path name for the image to be linked to an unique object? CoreData does not really handle unique IDs, and two objects can have the same name... I searched around objectID but it's not working really good and I'm not sure it's the good way to handle this.
Do you have any idea? Is there an other simple way I am totally missing? Thank you in advance.
use coredata's objectID as identifier
id uri = [self sanitizeFilename:coreDataObject.objectID.URIRepresentation];
[NSString stringWithFormat:#"%#.png", uri];
helper sanitizeFilename:
- (NSString *)sanitizeFileNameString:(NSString *)fileName {
NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:#"/\\?%*|\"<>"];
return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:#""];
}
Just create an object_id number property in your CoreData model entity description and each time a new object is created increment this property by one and assign it to the object, then use a naming convention like
[NSString stringWithFormat:#"object_%d_img.png", idNumber];
And save it to NSDoctumentsDirectory.
Then in object's - (void)prepareForDeletion method delete the image.
As for how to increment the id value, create a method that will fetch an object with biggest id value - simply get all objects with sort descriptor by id desc and use it + 1 when creating a new entity.
Thanks to #Daij-Djan. I created version for Swift:
var itemObjectId:String = item.objectID.URIRepresentation().absoluteString!
var fileName = NSString(format:"%#.png", FileHelper.sanitizeFileNameString(itemObjectId)) as String
Helper for sanitize:
struct FileHelper {
static func sanitizeFileNameString(fileName:String) ->String {
let illegalFileNameCharacters:NSCharacterSet = NSCharacterSet(charactersInString: "/\\?%*|\"<>")
let components : [String] = fileName.componentsSeparatedByCharactersInSet(illegalFileNameCharacters)
let joinedString = join("", components)
return joinedString
}
}
I think you'll need to generate the unique id by your self. Since a user can have several objects. so maybe the image id could be named as such
userId-objectId-somesalt
save the value to the object's path

Where does the Finder obtain the "date added" of an item in a folder?

If a folder is placed in the Dock you can sort it by "date added" - this is usually the default for the Downloads folder. (Sometimes the Finder does not appear to be using the date added but the date modified, but it can find the date added.) Where is the Finder figuring this out from? The standard file metadata, i.e. as obtained by stat, getattrlist or FSGetCatInfo) does not contain it. TIA
Yep, the date added could be inferred from other structures. In fact, it resides in Spotlight metadata.
NSDate *dateAdded(NSURL *url)
{
NSDate *rslt = nil;
MDItemRef inspectedRef = nil;
inspectedRef = MDItemCreateWithURL(kCFAllocatorDefault, (CFURLRef)url);
if (inspectedRef){
CFTypeRef cfRslt = MDItemCopyAttribute(inspectedRef, (CFStringRef)#"kMDItemDateAdded");
if (cfRslt) {
rslt = (NSDate *)cfRslt;
}
}
return rslt;
}
Note: out of date now that Lion’s out.
The Finder isn’t, the Dock is. It tracks this data internally. If you remove a folder and put it back, the “date added” information is lost for existing items.
Here's a Swift 5.x version of Wojtek's answer:
public extension URL {
var dateAdded: Date? {
if let metadataItemValue = MDItemCreateWithURL(kCFAllocatorDefault, (self as CFURL)) {
return MDItemCopyAttribute(metadataItemValue, kMDItemDateAdded) as? Date
}
return nil
}
}
I've tested this back to Swift 4.x, and I think it'll compile without modification back to Swift 3.x if you need that too. Just be aware that, before Swift 5, its inferred visibility would be internal rather than public.