How to convert FlutterStandardTypedData to NSArray? - objective-c

I have an app written in dart which uses a channel to call a method in Objective-C. The method needs data in form of an NSArray to act. I am passing this data as Uint8List from dart but in Objective-C, it shows that it's a FlutterStandardTypedData. Is there any way to convert that to an NSArray? Thanks in advance.

You will likely have to copy it out of the FlutterStandardTypedData using something like... (Note that in this example the typed data is doubles - you presumably have bytes)
if let args = call.arguments as? Dictionary<String, Any>,
let au = args["data"] as? FlutterStandardTypedData {
au.data.withUnsafeBytes{(pointer: UnsafeRawBufferPointer) in
let doubles = pointer.bindMemory(to: Double.self)
for index in 0..<Int(au.elementCount) {
// copy to the NSArray
}
}
result(nil)
} else {
result(FlutterError.init(code: "errorProcess", message: "data or format error", details: nil))
}

I'm having issues w/ FlutterStandardTypedData as well. From what i'm reading this should be serialized "auto-magically" on the iOS side as it's a supported data type. I can see on my end, for instance, that the length of the byte buffer is the value i'm expecting. My issue is I cannot seem to access a single value of the byte data in the same method i can see the length value. "Unrecognized selector for FlutterStandardTypedData" whenever i try to access it like an array...I cannot find good documentation either. If i use a simple data type, like string, things work out just fine. I'm only getting burned by the more complex data type(s)...
I figured it out, in the plugin you have to use FlutterStandardTypedData as the data type for the array, and then you can see the .data elements on the native iOS side. Without this data type, coming in to the iOS side i could "see" the data but would get memory exceptions every time i would try to access the data(objects/elements) in the list. Xcode was previously converting my NSArray to a FlutterStandardTypedData in the IDE (even though i specified NSArray NOT FlutterStandard...) auto-magically, but again, erroring out whenever i would try to work w/ the object. Simply changing from NSArray in plugin to FlutterStandardTypedData solved my problem, just took a while to figure out b/c the documentation wasn't very clear (that i came across).

Related

Make Whole Request UTF-8 from NSURLSession

I am making a simple NSURLSession GET request and i am returned the right data and i am able to serialize it up to one point where the data is no longer UTF-8 so i am unable to call keys of the children.
My data looks like this:
[
{
"GeoJsonData":"{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[-119.1968536376953,35.5229358991794],[-119.19696092605591,35.52019399894053],[-119.19206857681274,35.520141605030304],[-119.19204711914062,35.52003681710729],[-119.18736934661865,35.52007174643016],[-119.18730497360228,35.52213254957543],[-119.18839931488039,35.52215001378275],[-119.18842077255249,35.522813650845336],[-119.19696092605591,35.522918435143076]]}}",
"GeoJsonCenter":"{\"lat\":35.52148635814335,\"lng\":-119.1921329498291}"
},
{
"GeoJsonData":"{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[-112.42687225341795,33.49409462250672],[-112.42678642272949,33.47605511894646],[-112.42549896240234,33.47605511894646],[-112.42103576660156,33.48822503770075],[-112.41022109985352,33.49438093353938],[-112.42687225341795,33.49409462250672]]]}}",
"GeoJsonCenter":"{\"lat\":33.48521802624292,\"lng\":-112.41854667663574}"
}
]
As you can see there are alot of escape characters in there and i have 85 objects in this array i need to iterate over and once i get down to the children of these objects i am not able to call those objects.
example of my code:
NSMutableArray *geoJSONData = [[NSMutableArray alloc] init];
for (NSDictionary *item in jsonArray){
[geoJSONData addObject:[item objectForKey:#"GeoJsonData"]];
}
for (NSDictionary *item in geoJSONData) {
NSLog(#"%#", [item objectForKey:#"coordinates"]);
}
the last NSLog blows up the console because it is not able to find that key "coordinates" because it is wrapped with escaped characters and i need to get those out.
Has anyone ran into this issue and whats the best way to solve this so i can have my object working fully serialized as JSON.
any help is greatly appreciated, im just getting back into Objective-c from AngularJs and last time i worked with Objective-C i used NSUrlRequest...so things have changed.
If the data that you shown is the real representation of it then you have a small issue. The value for key GeoJsonData is not an object but a string. In other words it's an object that was serialized using JSON.stringify() and added to the parent object. Quite a strange construction, that's why I'm asking if that is the real JSON representation sent by the server.
What you'll need to do before trying to access the key coordinates is to JSON parse that string to get a valid object back so you can access it's properties as a normal NSDictionary, write now is just a string.
Just use NSJSONSerialization class to decode your GeoJsonData.

Line of code from Swift to Objective-C

I'm quite blank when it comes to swift, I've been developing using Obj-c. But a tutorial that I've been following uses Swift. Can anyone help me convert the following line of Swift into Objective-C. It's basically to load a String onto an Array.
self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)
self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)
Should be
[self.iDArray append: [objectIDs[1].valueForKey: #"objectID"]]
However, the Swift code is force-casting [objectIDs[1].valueForKey: #"objectID"] to type String (A Swift string).
That suggests to me that self.iDArray may be a Swift array. Swift arrays normally contain only a single type. You create an array of String objects, or an array of Dictionary objects. You can also create an array of AnyObject.
NSArray is an array of id type.
I'm not 100% positive how to force-cast to String type in Objective-C. maybe:
[self.iDArray append: (String) [objectIDs[1] valueForKey: #"objectID"]]
On the surface, objectIDs[x] appears to be a dictionary, and the compiler will give you a break on types if you dereference it that way. So naive to parse, a usable syntax would be:
[self.iDArray append:objectIDs[1][#"objectId"]];
But that's incorrect semantically for parse, since the implication is that the objectIDs array is implied to contain parse objects (named confusingly with the "IDs" suffix). If it's really parse objects, then the collection style reference for objectId won't work, and should be instead
[self.iDArray append:((PFObject *)objectIDs[1]).objectId];
Or more readably:
PFObject *object = objectIDs[1];
NSString *objectId = object.objectId;
[self.iDArray append:objectId];
But, along the same lines semantically, the implication of the code is that it's adding to an NSMutable array, so it probably should be -- for any of the above suggestions:
[self.iDArray addObject: .....
Stop reading here if you care only about compiling and executing without a crash.
But, even if all that's right, which I think can be inferred from the code, it's indicative of bad design in my opinion. Swift developers in particular seem to have a penchant for saving off objectIDs and passing them around as proxies for object, and in so doing, loosing all of the other valuable stuff in the PFObject.
My practice is, wherever possible, just keep and pass the whole PFObject. You can always ask it for its objectId, later. More strongly, my rule of thumb when reading code is: show me parse.com code that refers much to objectIds -- except for things like equality tests -- and I'll show you a design error.

NSString isEqual strange bug

I have a web server which I used to fetch some data in my iOS application. The data include a field as the itemId let say '48501' (with no quotation). I read item JSON data into my itemObject in which itemId is defined as a NSString and not a NSInteger.
Everything works until this point but I have problems where I want to compare itemObject.itemId using isEqual: function with another NSString filled with 48501.
In other words both string are exactly the same and include 48501 when I print them. No space and hidden things is there. All isEqual: and isEqualToString: and == report false on comparison.
On the hand when I convert NSStrings to NSIntegers and compare them it works but not always! sometime TRUE sometime CRASH with no error to catch and just pointing to the line! I see them printed exactly the same but the if statement does not go through.
I showed the code to someone with far more experience than me and he was like this could be a bug! Anyone has ever exposed to this?
If your itemId is 48501 without any quotation in the JSON, then it's deserialized as NSNumber. Probably that's the problem in the first place. Try logging the type of your itemId and use appropriately -isEqualToString: for NSString and -isEqualToNumber: for NSNumber.

How to dynamically typecast objects to support different versions of an application's ScriptingBridge header files?

Currently I'm trying to implement support for multiple versions of iTunes via ScriptingBridge.
For example the method signature of the property playerPosition changed from (10.7)
#property NSInteger playerPosition; // the player’s position within the currently playing track in seconds.
to (11.0.5)
#property double playerPosition; // the player’s position within the currently playing track in seconds
With the most current header file in my application and an older iTunes version the return value of this property would always be 3. Same thing goes the other way around.
So I went ahead and created three different iTunes header files, 11.0.5, 10.7 and 10.3.1 via
sdef /path/to/application.app | sdp -fh --basename applicationName
For each version of iTunes I adapted the basename to inlcude the version, e.g. iTunes_11_0_5.h.
This results in the interfaces in the header files to be prefixed with their specific version number.
My goal is/was to typecast the objects I'd use with the interfaces of the correct version.
The path to iTunes is fetched via a NSWorkspace method, then I'm creating a NSBundle from it and extract the CFBundleVersion from the infoDictionary.
The three different versions (11.0.5, 10.7, 10.3.1) are also declared as constants which I compare to the iTunes version of the user via
[kiTunes_11_0_5 compare:versionInstalled options:NSNumericSearch]
Then I check if each result equals NSOrderedSame, so I'll know which version of iTunes the user has installed.
Implementing this with if statement got a bit out of hand, as I'd need to do these typecasts at many different places in my class and I then started to realize that this will result in a lot of duplicate code and tinkered around and thought about this to find a different solution, one that is more "best practice".
Generally speaking, I'd need to dynamically typecast the objects I use, but I simply can't find a solution which wouldn't end in loads of duplicated code.
Edit
if ([kiTunes_11_0_5 compare:_versionString options:NSNumericSearch] == NSOrderedSame) {
NSLog(#"%#, %#", kiTunes_11_0_5, _versionString);
playerPosition = [(iTunes_11_0_5_Application*)_iTunes playerPosition];
duration = [(iTunes_11_0_5_Track*)_currentTrack duration];
finish = [(iTunes_11_0_5_Track*)_currentTrack finish];
} else if [... and so on for each version to test and cast]
[All code directly entered into answer.]
You could tackle this with a category, a proxy, or a helper class, here is a sketch of one possible design for the latter.
First create a helper class which takes and instance of your iTunes object and the version string. Also to avoid doing repeated string comparisons do the comparison once in the class setup. You don't give the type of your iTunes application object so we'll randomly call it ITunesAppObj - replace with the correct type:
typedef enum { kEnumiTunes_11_0_5, ... } XYZiTunesVersion;
#implementation XYZiTunesHelper
{
ITunesAppObj *iTunes;
XYZiTunesVersion version;
}
- (id) initWith:(ITunesAppObj *)_iTunes version:(NSString *)_version
{
self = [super self];
if (self)
{
iTunes = _iTunes;
if ([kiTunes_11_0_5 compare:_version options:NSNumericSearch] == NSOrderedSame)
version = kEnumiTunes_11_0_5;
else ...
}
return self;
}
Now add an item to this class for each item which changes type between versions, declaring it with whatever "common" type you pick. E.g. for playerPosition this might be:
#interface XYZiTunesHelper : NSObject
#property double playerPosition;
...
#end
#implementation XYZiTunesHelper
// implement getter for playerPosition
- (double) playerPosition
{
switch (version)
{
case kEnumiTunes_11_0_5:
return [(iTunes_11_0_5_Application*)_iTunes playerPosition];
// other cases - by using an enum it is both fast and the
// compiler will check you cover all cases
}
}
// now implement the setter...
Do something similar for track type. Your code fragment then becomes:
XYZiTunesHelper *_iTunesHelper = [[XYZiTunesHelper alloc] init:_iTunes
v ersion:_versionString];
...
playerPosition = [_iTunesHelper playerPosition];
duration = [_currentTrackHelper duration];
finish = [_currentTrackHelper finish];
The above is dynamic as you requested - at each call there is a switch to invoke the appropriate version. You could of course make the XYZiTunesHelper class abstract (or an interface or a protocol) and write three implementations of it one for each iTunes version, then you do the test once and select the appropriate implementation. This approach is more "object oriented", but it does mean the various implementations of, say, playerPosition are not together. Pick whichever style you feel most comfortable with in this particular case.
HTH
Generating multiple headers and switching them in and out based on the application's version number is a really bad 'solution': aside from being horribly complicated, it is very brittle since it couples your code to specific iTunes versions.
Apple events, like HTTP, were designed by people who understood how to construct large, flexible long-lived distributed systems whose clients and servers could evolve and change over time without breaking each other. Scripting Bridge, like a lot of the modern 'Web', was not.
...
The correct way to retrieve a specific type of value is to specify your required result type in the 'get' event. AppleScript can do this:
tell app "iTunes" to get player position as real
Ditto objc-appscript, which provides convenience methods specifically for getting results as C numbers:
ITApplication *iTunes = [ITApplication applicationWithBundleID: #"com.apple.itunes"];
NSError *error = nil;
double pos = [[iTunes playerPosition] getDoubleWithError: &error];
or, if you'd rather get the result as an NSNumber:
NSNumber *pos = [[iTunes playerPosition] getWithError: &error];
SB, however, automatically sends the 'get' event for you, giving you no what to tell it what type of result you want before it returns it. So if the application decides to return a different type of value for any reason, SB-based ObjC code breaks from sdp headers onwards.
...
In an ideal world you'd just ditch SB and go use objc-appscript which, unlike SB, knows how to speak Apple events correctly. Unfortunately, appscript is no longer maintained thanks to Apple legacying the original Carbon Apple Event Manager APIs without providing viable Cocoa replacements, so isn't recommended for new projects. So you're pretty much stuck with the Apple-supplied options, neither of which is good or pleasant to use. (And then they wonder why programmers hate everything AppleScript so much...)
One solution would be to use AppleScript via the AppleScript-ObjC bridge. AppleScript may be a lousy language, but at least it knows how to speak Apple events correctly. And ASOC, unlike Cocoa's crappy NSAppleScript class, takes most of the pain out of gluing AS and ObjC code together in your app.
For this particular problem though, it is possible to monkey-patch around SB's defective glues by dropping down to SB's low-level methods and raw four-char codes to construct and send the event yourself. It's a bit tedious to write, but once it's done it's done (at least until the next time something changes...).
Here's a category that shows how to do this for the 'player position' property:
#implementation SBApplication (ITHack)
-(double)iTunes_playerPosition {
// Workaround for SB Fail: older versions of iTunes return typeInteger while newer versions
// return typeIEEE64BitFloatingPoint, but SB is too stupid to handle this correctly itself
// Build a reference to the 'player position' property using four-char codes from iTunes.sdef
SBObject *ref = [self propertyWithCode:'pPos'];
// Build and send the 'get' event to iTunes (note: while it is possible to include a
// keyAERequestedType parameter that tells the Apple Event Manager to coerce the returned
// AEDesc to a specific number type, it's not necessary to do so as sendEvent:id:parameters:
// unpacks all numeric AEDescs as NSNumber, which can perform any needed coercions itself)
NSNumber *res = [self sendEvent:'core' id:'getd' parameters: '----', ref, nil];
// The returned value is an NSNumber containing opaque numeric data, so call the appropriate
// method (-integerValue, -doubleValue, etc.) to get the desired representation
return [res doubleValue];
}
#end
Notice I've prefixed the method name as iTunes_playerPosition. Unlike objc-appscript, which uses static .h+.m glues, SB dynamically creates all of its iTunes-specific glue classes at runtime, so you can't add categories or otherwise patch them directly. All you can do is add your category to the root SBObject/SBApplication class, making them visible across all classes in all application glues. Swizzling the method names should avoid any risk of conflict with any other applications' glue methods, though obviously you still need to take care to call them on the right objects otherwise you'll likely get unexpected results or errors.
Obviously, you'll have to repeat this patch for any other properties that have undergone the same enhancement in iTunes 11, but at least once done you won't have to change it again if, say, Apple revert back to integers in a future release or if you've forgotten to include a previous version in your complicated switch block. Plus, of course, you won't have to mess about generating multiple iTunes headers: just create one for the current version and remember to avoid using the original -playerPosition and other broken SB methods in your code and use your own robust iTunes_... methods instead.

Objective-C, Buzztouch coding alerts - Data argument not used by format string and Semantic issue. Can someone explain what is going on?

I'm currently running Mountain Lion OS X 10.8 with Xcode 4.4 installed. I'm running the iOS 5.1 simulator. I'm using Buzztouch as a learning tool while I'm studying Objective-C and Xcode. I get the following alerts when I compile, but the build succeeds. However, I would like to know exactly what is going on and how I can remedy the situation. Thank you for any assistance you can provide. Here's the code and the alerts I'm getting:
BT_fileManager.m
Data argument not used by format string
[BT_debugger showIt:self:[NSString stringWithFormat:#"readTextFileFromBundleWithEncoding ERROR using encoding NSUTF8StringEncoding, trying NSISOLatin1StringEncoding", #""]];
Data argument not used by format string
[BT_debugger showIt:self:[NSString stringWithFormat:#"readTextFileFromCacheWithEncoding ERROR using encoding NSUTF8StringEncoding, trying NSISOLatin1StringEncoding", #""]];
BT_camera_email.m
Semantic Issue
Sending 'BT_camera_email *' to parameter of incompatible type 'id'
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
NSLog(#"is camera ok");
UIActionSheet *photoSourceSheet = [[UIActionSheet alloc] initWithTitle:#"Select Image Source"
delegate:self
Again, thanks.
Greg
I have no idea what Buzztouch might be, however.... :-)
The first warning is fairly simple. In a format string there are placeholders beginning with a '%' sign to indicate where data values should be substituted. For example, to substitute a string, one would use '%#'. In the examples you show, there are no placeholders but there are data values -- empty strings. The compiler is warning that something you indicate you want to have put into the new string created by stringWithFormat: won't be.
To be sure about the second one, I'd want to see the .h file that declares BT_camera_email but my best guess is that it doesn't adopt the UIActionSheetDelegate protocol. The description of initWithTitle:... says the second parameter should be id<UIActionSheetDelegate> and that's probably what is being complained about.