Good evening,
I'm currently trying to produce a list of all available serial ports in Swift using the ORSSerialPort Objective-C library. The current code is below, this just generates the NSArray that contains the available ports.
import Foundation
import Cocoa
class Serial {
init() {
}
#IBOutlet var serialListPullDown : NSPopUpButton!
func refreshSerialList(defaultprompt: String) {
//Initialize ORSSerialPortManager
let portManager : ORSSerialPortManager = ORSSerialPortManager.sharedSerialPortManager()
var availablePorts : NSArray = portManager.availablePorts
//Erase entries from popup field
serialListPullDown?.removeAllItems()
}
}
Currently, when I insert a breakpoint at:
var availablePorts : NSArray = portManager.availablePorts
When I work through the debug window (http://imgur.com/NcXnJig) I see that I can find the path I'm looking for, in this case '/dev/cu.Bluetooth-Modem'. However this information seems to be hidden behind _path which should be a variable of the ORSSerialPortManager class but I cannot find it in the source files. Obviously the information is there, but how do I get to it in my Swift function?
availablePorts is an NSArray of ORSSerialPort objects. It looks like you can directly access the path property to get the data you're looking for.
var availablePorts : NSArray = portManager.availablePorts
for port in availablePorts as [ORSSerialPort] {
println("Serial Port: \(port.path)");
}
Related
I am trying to fetch data from CoreData and return it as an array for charting in a popular charting library. The code below runs fine and I can print the data to the console, however I want to fill self.hkdataBase with the entries within CoreData and Return it. Any idea what I am doing wrong ?
class ViewController: UIViewController {
var hkdataBase = [HKdataBase]()
....
func fetchCoreData () -> NSArray {
//Setting up Core Data
var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext!
var request = NSFetchRequest(entityName: "HKdataBase")
request.returnsObjectsAsFaults = false
//Fetching Data
self.hkdataBase = context.executeFetchRequest(request, error: nil)! as [HKdataBase]
if hkdataBase.count > 0 {
for i in hkdataBase {
**I WANT TO FILL self.hkdataBase WITH i ELEMENTS HERE ** -> println(i.hr_data) WORKS FINE
}
} else {
println("No results")
}
}
**return self.hkdataBase with elements**
}
UPDATE 1:
I want to Return an Array from the fetched data in CoreData. The hr_data are Heart Rate measures and hr_date are the associated NSDate. The HKdataBase looks like this:
import Foundation
import CoreData
class HKdataBase: NSManagedObject {
#NSManaged var hr_date: NSDate
#NSManaged var hr_data: NSNumber
}
After the fetch, you already have your managed objects in self.hkdataBase. Managed objects are KVC compliant, so to get just one kind of value out if it is quite simple.
var hrData = (self.hkdataBase as NSArray).valueForKey("hr_data") as NSArray
You now have an array containing your hr_data, presumably an array of NSNumber objects.
It's been asked before, but no clear (current) answer seems to be out there.. Is it actually possible to build a Cocoa app, WITH a Main Menu, exclusively from code (no MainMenu.xib, etc.) in such a way that it will still pass scrutiny when submitted to the app store? If so, what is the magic incantation(s) to get this to work?
Extra credit if someone can point me to a tutorial or document that's not from 2002 and works on mavericks..
Well, it certainly used to be possible.
I’d start by looking in main.m, and replace NSApplicationMain() with NSApplicationLoad(), so you get an NSApplication object.
Then you can create an NSMenu using standard NSMenu methods (-addItem:, etc), and then call
[NSApplication sharedApplication].mainMenu = myMenu;
Then, you know, make an NSWindow, show that, etc.
Of course, there are a lot of menu items that Apple sets up for you when you launch, that you might not get when you do this. You’d have to add them by hand if so.
This really isn’t something I recommend, but there you go.
http://blog.moostep.com/xamarin-mac-helloworld-application-without-xib/
http://blog.moostep.com/creating-menu-for-xamarin-mac-app-using-csharp/
I don't know enough about Mac App Store to know if this will pass muster. I assume you can translate it from C# to Objective-C. It doesn't use any special Mono or Xamarin features.
Read the blog articles for some background. Meanwhile, I'll paste my versions of main.cs and AppDelegate.cs here:
main.cs:
using System;
using MonoMac.AppKit;
namespace XibFreeCocoaApp
{
public class XibFreeCocoaApp
{
static void Main (string[] args)
{
NSApplication.Init ();
var application = NSApplication.SharedApplication;
application.Delegate = new AppDelegate();
application.Run ();
}
}
}
AppDelegate.cs:
using System;
using System.Drawing;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace XibFreeCocoaApp
{
public class AppDelegate : NSApplicationDelegate
{
public override void FinishedLaunching (MonoMac.Foundation.NSObject notification)
{
CreateMenu (NSProcessInfo.ProcessInfo.ProcessName);
var window = new NSWindow (
new RectangleF (0, 0, 400, 300),
NSWindowStyle.Titled,
NSBackingStore.Buffered,
false) {
Title = "Xib Free Cocoa App with Menu"
};
window.CascadeTopLeftFromPoint (new PointF (20, 20));
window.MakeKeyAndOrderFront(null);
}
void CreateMenu (string appName)
{
var mainMenu = new NSMenu();
var appMenuItem = new NSMenuItem ();
mainMenu.AddItem (appMenuItem);
var appMenu = new NSMenu ();
var quitMenuItem = new NSMenuItem (String.Format ("Quit {0}", appName), "q", delegate {
NSApplication.SharedApplication.Terminate(mainMenu);
});
appMenu.AddItem (quitMenuItem);
appMenuItem.Submenu = appMenu;
NSApplication.SharedApplication.MainMenu = mainMenu;
}
}
}
Be aware that the code above will not change the title of menu items that have a submenu - to do this you need to assign title to the Submenu as well like so:
NSMenuItem someMenuItem = new NSMenuItem("Title 1");
NSMenu someMenuItemSubMenu = new NSMenu();
someMenuItemSubMenu.Title = "Title 2";
someMenuItem.Submenu = someMenuItemSubMenu;
The displayed tile in this case will be "Title 2", not "Title 1" (actually "Title 1" will be completely ignored).
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.
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!
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.