asyncudpsocket does not send UDP as expected - udp

I have XCODE 3.1.4 running ona mini MAC 10.5.8 and Simulator 3.1
I want to send a short UDP string for some remote control and have made the following code
Basicly it does compile and run in the simulator ... but it nevers send any UDP to the target. I hope someone can give me a clue why it does not work
My .H code
#import <UIKit/UIKit.h>
#import "AsyncUdpSocket.h"
#import "AsyncSocket.h"
#interface ChangeLabelViewController : UIViewController {
IBOutlet UILabel *label ;
AsyncUdpSocket *socket;
}
-(IBAction) ChangeLabel;
-(IBAction) ResetLabel;
#end
My .m code
#import "ChangeLabelViewController.h"
#implementation ChangeLabelViewController
-(IBAction) ChangeLabel
{
label.text = #"Hello";
}
-(IBAction) ResetLabel
{
label.text = #"Empty";
NSLog(#"%s", __PRETTY_FUNCTION__);
NSString * string = #"Testing iPhone";
NSString * address = #"192.168.1.11";
UInt16 port = 1234;
NSData * data = [string dataUsingEncoding: NSUTF8StringEncoding];
if ([socket sendData:data toHost:address port:port withTimeout:- 1 tag:1]) label.text = #"Send";
// if ([socket sendData:data toHost:address port:port withTimeout:-1 tag:1] == YES) label.text = #"Yes";
// if ([socket sendData:data toHost:address port:port withTimeout:-1 tag:1] == NO) then label.text = #"No";
;
}
#end

Had to init the socket
under - (void) vievDidLoad
socket = [[AsyncUdpSocket alloc] initWithDelegate:self];
Then it worked as expected :-)

If you are staring from a brand new project you will also need to do the following:
1. add CFNetwork to your frameworks in the project
2. add the cocaasyncsockets files to your project
Instructions are here: http://code.google.com/p/cocoaasyncsocket/wiki/iPhone
Pay attention to the instructions on how to add CFNetwork, it is not shown in the list of available options.
Hint: you will need to use the finder to select a path, I am a mac novice so it took me a while to figure out that I had to use Go/Go To Folder....

Related

Why is the path of NSApplicationSupportDirectory not the same in Cocoa app and console app?

I made a small tool and needed to access the Application Support directory of the user layer, so I created a command line project, used URLsForDirectory to get the path, and everything worked fine.
But when I create a cocoa project with a gui, the path it returns is under the Containers directory, which doesn't seem to exist.
What's causing this discrepancy? What should I do to get the ~/Library/Application Support directory in the cocoa project?
this is the code:
#import "ViewController.h"
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSArray* pathes = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask
];
NSString* applicationSupportPath = [pathes firstObject];
NSLog(#"Application Support:%#\n", applicationSupportPath);
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
#end
the output is :
2022-10-03 22:01:23.230600+0800 TestApplicationSupportPath[49579:213899] Application Support:file:///Users/bodong/Library/Containers/com.bodong.TestApplicationSupportPath/Data/Library/Application%20Support/
console :
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
// insert code here...
NSLog(#"Hello, World!");
}
NSArray* pathes = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask
];
NSString* applicationSupportPath = [pathes firstObject];
NSLog(#"Application Support:%#\n", applicationSupportPath);
return 0;
}
the output is :
2022-10-03 22:02:09.341780+0800 TestASPCmd[49791:215344] Application Support:file:///Users/bodong/Library/Application%20Support/
Program ended with exit code: 0
I found a solution, just in the project properties, switch to Signing&Capabilities, delete the Sanbox group.

MLKit object detector is crashing in MLKObjectDetectorOptions

I am trying to fetch object frames from given image using MKLKIT. But my code is getting crashed
MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init];
#import <Foundation/Foundation.h>
#import <MLKitObjectDetection/MLKitObjectDetection.h>
#import <MLKitObjectDetectionCommon/MLKObjectDetector.h>
#import <MLKitObjectDetection/MLKObjectDetectorOptions.h>
#import <MLKitObjectDetectionCommon/MLKObject.h>
#import <MLKitVision/MLKVisionImage.h>
#import "MLKitObjectDetection.h"
#implementation MLObjectDetection
- (NSMutableArray*)detectFrame:(UIImage*)image{
NSMutableArray *frames = [NSMutableArray new];
// Multiple object detection in static images
MLKObjectDetectorOptions *options = [[MLKObjectDetectorOptions alloc] init];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableMultipleObjects = YES;
MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
visionImage.orientation = image.imageOrientation;
NSError *error;
NSArray *objects = [objectDetector resultsInImage:visionImage error:&error];
if (error == nil) {
return frames;
}
if (objects.count == 0) {
// No objects detected.
}
for (MLKObject *object in objects) {
[frames addObject:[NSValue valueWithCGRect:object.frame]];
}
//TODO release memory
return frames;
}
#end
When your code crash, did you try to run your code inside Xcode and look into the console in the debug area to check what error message was printed out there? Usually that will give you some clue as to what led to the crash.
Based on your code, are you calling the detectFrame: method from the main UI thread? The synchronous MLKObjectDetector#resultsInImage:error: should never be called from the main UI thread. This is documented in its API reference. You can check out ML Kit's quickstart sample app here. It shows how to call both the synchronous MLKObjectDetector#resultsInImage:error: API and the asynchronous MLKObjectDetector#processImage:completion: API.

worklight 6.0 adapter native ios to hybrids application

I can able to call worklight 6.0 adapter invoke in IOS native code (using Objective-C) but i can not read adapter JSON response using cordova plugin from my hybrids application.
// invoke the adapter
MyConnectListener *connectListener = [[MyConnectListener alloc] initWithController:self];
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];
// calling the adapter using objective-c
WLProcedureInvocationData *myInvocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"HTTP_WS_ADPTR" procedureName:#"getBalance"];
MyInvokeListener *invokeListener = [[MyInvokeListener alloc] initWithController: self];
[[WLClient sharedInstance] invokeProcedure:myInvocationData withDelegate:invokeListener];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:responseString];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
// hybrids application call the native code
cordova.exec(sayHelloSuccess, sayHelloFailure, "HelloWorldPlugin", "sayHello", [name]);
above the cordova.exec success and failed method is not return the value.
but i can not able to parse the value from CDVPluginResult method. Anybody please advice me. how can i read the adapter for IOS native from hybrids application.
Several things to note:
You are using Worklight 6.0.0.x. In Worklight 6.0.0.x there is no proper session sharing between web and native views. Meaning, if you will for example call the WL.Client.connect() method in the web view and then do a connect() and adapter invocation in the native view - these calls will not share the same session which can lead to race condition errors, inability to share state between the views and other unexpected events. Not recommended.
If this is the approach you're looking to implement in your Hybrid application it is therefore highly recommended that you will upgrade to either MobileFirst (previous known as "Worklight") v6.3 or v7.0 where session sharing between web and native views is now available out-of-the-box.
Although you might just want to opt to call the adapter from the JS code...
To get this to work as-is in your supplied project, you can change the implementation based on the below.
Note that the implementation below was based on MFP 7.0, as such the adapter invocation code will not work in your 6.0.0.0x codebase. You will need to alter it based on your own code in v6.0.0.x:
sayHello.h
#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
#import "WLClient.h"
#import "WLDelegate.h"
#interface SayHelloPlugin : CDVPlugin
- (void)sayHello:(CDVInvokedUrlCommand*)command;
- (void)callResult:(NSString*)response;
#end
sayHello.m
#import "SayHelloPlugin.h"
#import "MyConnectListener.h"
CDVInvokedUrlCommand *tempCommand;
#implementation SayHelloPlugin
- (void)sayHello:(CDVInvokedUrlCommand*)command {
MyConnectListener *connectListener = [[MyConnectListener alloc] init:self];
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];
tempCommand = command;
}
-(void)callResult:(NSString*)response{
CDVPluginResult *pluginResult =
[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:response];
[self.commandDelegate sendPluginResult:pluginResult callbackId:tempCommand.callbackId];
}
#end
MyConnectListener.h
#import <Foundation/Foundation.h>
#import "WLClient.h"
#import "WLDelegate.h"
#import "SayHelloPlugin.h"
#interface MyConnectListener : NSObject <WLDelegate> {
#private
SayHelloPlugin *sh;
}
- (id)init: (SayHelloPlugin *)sayHello;
#end
MyConnctListener.m
The responseText line is commented out because the data retrieved from the adapter was too large I suppose, so it's best to return only what you really need and not all of it.
#import "MyConnectListener.h"
#import "WLResourceRequest.h"
NSString *resultText;
NSString *request;
#implementation MyConnectListener
- (id)init: (SayHelloPlugin *) sayHello{
if ( self = [super init] )
{
sh = sayHello;
}
return self;
}
-(void)onSuccess:(WLResponse *)response{
NSURL* url = [NSURL URLWithString:#"/adapters/testAdapter/getStories"];
WLResourceRequest* request = [WLResourceRequest requestWithURL:url method:WLHttpMethodGet];
[request setQueryParameterValue:#"['technology']" forName:#"params"];
[request sendWithCompletionHandler:^(WLResponse *response, NSError *error) {
if(error != nil){
resultText = #"Invocation failure: ";
resultText = [resultText stringByAppendingString: error.description];
[sh callResult:resultText];
}
else{
resultText = #"Invocation success. ";
//resultText = [resultText stringByAppendingString:response.responseText];
[sh callResult:resultText];
}
}];
}
-(void)onFailure:(WLFailResponse *)response{
resultText = #"Connection failure: ";
resultText = [resultText stringByAppendingString:[response errorMsg]];
NSLog(#"***** failure response: %#", resultText);
[sh callResult:resultText];
}
#end

SpriteKit .sks files and subclassing

Apple demoed this code in their WWDC 2014 Session 608 video on best practices for SpriteKit.
AppDelegate.m
+ (instancetype)unarchiveFromFile:(NSString *)file {
/* Retrieve scene file path from the application bundle */
NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:#"sks"];
/* Unarchive the file to an SKScene object */
NSData *data = [NSData dataWithContentsOfFile:nodePath
options:NSDataReadingMappedIfSafe
error:nil];
NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[arch setClass:self forClassName:#"SKScene"];
SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
[arch finishDecoding];
return scene;
}
I understand the gist of what it's doing, but what I'm confused about is how to utilize this code in for any other .sks file. I tried calling the unarchiveFromFile method from my GameScene.m class, but to no avail. I read the post here on this topic, but it did not clarify things.
EDIT
As per what was suggested by Okapi, I tried the following in a new OS X SceneKit project in the GameScene.m class:
#import "GameScene.h"
#implementation GameScene
-(void)didMoveToView:(SKView *)view {
SKNode *nodeInScene2 = [self childNodeWithName:#"object1"];
for (SKNode *blah in [SKScene unarchiveFromFile:#"Scene2"].children) {
[nodeInScene2 addChild:blah];
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
#end
I have 2 .sks files. The first is called GameScene.sks and that has a sprite in there called "object1". I would like to add children stored in "Scene2.sks". The loop in the didMoveToView method gives me an error. What am I doing wrong? This is what Apple did in their WWDC 608 video, but perhaps I'm missing something since I can't find their project online.
+unarchiveFromFile: is defined as a category on SKScene in GameViewController.m. You would need to copy that code if you want to use it somewhere else.
#implementation SKScene (Unarchive)
+ (instancetype)unarchiveFromFile:(NSString *)file {
/* Retrieve scene file path from the application bundle */
NSString *nodePath = [[NSBundle mainBundle] pathForResource:file ofType:#"sks"];
/* Unarchive the file to an SKScene object */
NSData *data = [NSData dataWithContentsOfFile:nodePath
options:NSDataReadingMappedIfSafe
error:nil];
NSKeyedUnarchiver *arch = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[arch setClass:self forClassName:#"SKScene"];
SKScene *scene = [arch decodeObjectForKey:NSKeyedArchiveRootObjectKey];
[arch finishDecoding];
return scene;
}
#end
This one hung me up for a while too. I ended up declaring unarchiveFromFile in every subclass that needed it, then calling it when I wanted to transition scenes. Something like this...
if (contactQuery == (playerCategory | proceedCategory)) {
SKScene *levelTwo = [LevelTwo unarchiveFromFile:#"LevelTwo"];
[self.view presentScene:levelTwo transition:[SKTransition doorsCloseHorizontalWithDuration:0.5]];
}
Full sample code can be downloaded here.

Use camera scan QRCode or BarCode in ObjectiveC

I want to build an app to scan QRCode and Barcode. I want to use camera scan image contains the code (QRCode or BarCode) but not take photo. Now I have no idea to do it. Anyone, give some references, please!
You should look at: http://zbar.sourceforge.net/
Download the ZBarSDK and import it in pch file then use this code
// BarCodeView.h
#interface BarCodeView : UIViewController < ZBarReaderDelegate > {
UIImageView *resultImage;
UITextView *resultText;
}
#property (nonatomic, retain) IBOutlet UIImageView *resultImage;
#property (nonatomic, retain) IBOutlet UITextView *resultText;
- (IBAction) scanButtonTapped;
// BarCodeView.m
#synthesize resultImage, resultText;
- (IBAction) scanButtonTapped
{
NSLog(#"TBD: scan barcode here...");
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
// EXAMPLE: disable rarely used I2/5 to improve performance
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
// present and release the controller
[self presentModalViewController: reader
animated: YES];
[reader release];
}
- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info
{
// ADD: get the decode results
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results)
// EXAMPLE: just grab the first barcode
break;
// EXAMPLE: do something useful with the barcode data
resultText.text = symbol.data;
// EXAMPLE: do something useful with the barcode image
resultImage.image =
[info objectForKey: UIImagePickerControllerOriginalImage];
// ADD: dismiss the controller (NB dismiss from the *reader*!)
[reader dismissModalViewControllerAnimated: YES];
}
The two most active projects are ZBar and ZXing.
You didn't mention if you were targeting iOS or OS X. I don't believe ZBar suports OS X. ZXing does. I believe ZBar has better support for 1D codes than the C++-based ports of ZXing.
(FWIW, I'm an active contributor to the C++/OS X/iOS port of ZXing.)