For a private project I'm trying to use the private MobileWiFi framework in Swift.
I found this website:
http://iphonedevwiki.net/index.php/MobileWiFi.framework
In Objective-C it's working like a charm, but I want to convert the code to Swift.
I have converted the function "Retrieving a list of known networks" into Swift already and that function is working.
Now I'm trying to convert the "Getting the WiFi signal strength" function but the uses a callback function and I have tried so hard, but can't get it to work.
#include <MobileWiFi.h>
static WiFiManagerRef _manager;
static void scan_callback(WiFiDeviceClientRef device, CFArrayRef results, CFErrorRef error, void *token);
int main(int argc, char **argv)
{
_manager = WiFiManagerClientCreate(kCFAllocatorDefault, 0);
CFArrayRef devices = WiFiManagerClientCopyDevices(_manager);
if (!devices) {
fprintf(stderr, "Couldn't get WiFi devices. Bailing.\n");
exit(EXIT_FAILURE);
}
WiFiDeviceClientRef client = (WiFiDeviceClientRef)CFArrayGetValueAtIndex(devices, 0);
WiFiManagerClientScheduleWithRunLoop(_manager, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
WiFiDeviceClientScanAsync(client, (CFDictionaryRef)[NSDictionary dictionary], scan_callback, 0);
CFRelease(devices);
CFRunLoopRun();
return 0;
}
static void scan_callback(WiFiDeviceClientRef device, CFArrayRef results, CFErrorRef error, void *token)
{
NSLog(#"Finished scanning! networks: %#", results);
WiFiManagerClientUnscheduleFromRunLoop(_manager);
CFRelease(_manager);
CFRunLoopStop(CFRunLoopGetCurrent());
}
Can someone explain to me how to use such a callback function in the swift language?
Thanks in advance!
I found this function:
pcap_loop(pcapSession, numberOfPackets,
{
(args: UnsafeMutablePointer<u_char>,
pkthdr:UnsafePointer<pcap_pkthdr>,
packet: UnsafePointer<u_char>) ->Void in
// singleton call
let pa = PacketAnalyser.sharedInstance
pa.Process()
},
nil)
On this website: http://diydeveloper.io/tech/2015/11/27/swift-pcap
I think this is a posible solution for my problem. Can somebody explain to me if I can use this example?
Related
I wanna install a ipa on a jailbreak i-device.I get this code bellow on google. Here is the code
#import "dlfcn.h"
typedef int (*MobileInstallationInstall)(NSString *path, NSDictionary *dict, void *na, NSString *path2_equal_path_maybe_no_use);
void *lib = dlopen("/System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation", RTLD_LOCAL);
if (lib)
{
MobileInstallationInstall pMobileInstallationInstall = (MobileInstallationInstall)dlsym(lib, "MobileInstallationInstall");
if (pMobileInstallationInstall)
{
int ret = pMobileInstallationInstall(path, [NSDictionary dictionaryWithObject:#"User" forKey:#"ApplicationType"], nil, path);
dlclose(lib);
return ret;
}
}
return -1;
But that's not enough.I wanna get the install progress.Just like download progress. Unfortunately,I get nothing on google.any ideas?
you have to specify a callback function on the third parameter of MobileInstallationInstall
void MobileInstallationCallback(CFDictionaryRef information){
NSLog(#"%#",information);
}
int ret = pMobileInstallationInstall(path, [NSDictionary dictionaryWithObject:#"User" forKey:#"ApplicationType"], & MobileInstallationCallback, path);
all the informations will be sent to MobileInstallationCallback via the parameter information
I'm having a hard time, searching how to play a video file from a TMemoryStream (or a similar buffer in memory) using FFMpeg. I've seen many things, including UltraStarDX, expensive FFMpeg components for Delphi and so on.
One component called FFMpeg Vcl Player claims to play video formats from a memory stream. I downloaded the trial version and I guess it uses CircularBuffer.pas for that matter (maybe).
Does any one know how to do this?
Edit:
Now the better question is how to play an encrypted video file, using FFMpeg or similar libraries.
To play video from memory stream, you can use custom AVIOContext.
static const int kBufferSize = 4 * 1024;
class my_iocontext_private
{
private:
my_iocontext_private(my_iocontext_private const &);
my_iocontext_private& operator = (my_iocontext_private const &);
public:
my_iocontext_private(IInputStreamPtr inputStream)
: inputStream_(inputStream)
, buffer_size_(kBufferSize)
, buffer_(static_cast<unsigned char*>(::av_malloc(buffer_size_))) {
ctx_ = ::avio_alloc_context(buffer_, buffer_size_, 0, this,
&my_iocontext_private::read, NULL, &my_iocontext_private::seek);
}
~my_iocontext_private() {
::av_free(ctx_);
::av_free(buffer_);
}
void reset_inner_context() { ctx_ = NULL; buffer_ = NULL; }
static int read(void *opaque, unsigned char *buf, int buf_size) {
my_iocontext_private* h = static_cast<my_iocontext_private*>(opaque);
return h->inputStream_->Read(buf, buf_size);
}
static int64_t seek(void *opaque, int64_t offset, int whence) {
my_iocontext_private* h = static_cast<my_iocontext_private*>(opaque);
if (0x10000 == whence)
return h->inputStream_->Size();
return h->inputStream_->Seek(offset, whence);
}
::AVIOContext *get_avio() { return ctx_; }
private:
IInputStreamPtr inputStream_; // abstract stream interface, You can adapt it to TMemoryStream
int buffer_size_;
unsigned char * buffer_;
::AVIOContext * ctx_;
};
//// ..........
/// prepare input stream:
IInputStreamPtr inputStream = MyCustomCreateInputStreamFromMemory();
my_iocontext_private priv_ctx(inputStream);
AVFormatContext * ctx = ::avformat_alloc_context();
ctx->pb = priv_ctx.get_avio();
int err = avformat_open_input(&ctx, "arbitrarytext", NULL, NULL);
if (err < 0)
return -1;
//// normal usage of ctx
//// avformat_find_stream_info(ctx, NULL);
//// av_read_frame(ctx, &pkt);
//// etc..
You can waste your time rewriting FFMPEG from C++ to Delphi, or mess with wrapper libraries.
Or if you're just interested in playing a video in Delphi, then check out Mitov's VideoLab components.
http://www.mitov.com/products/videolab#components
If you want play Stream from memory you can make a virtual memory. I suggest BoxedAppSdk.
This will help you to make a virtual drive with virtual files that you can write on it and then give the virtual path to the player component that you have.
BoxedApp is not free but it is really awesome and very simple in use!
I am currently using an EtherTen to try and connect Arduino to Twitter. However, I keep getting an error saying "'twitter'does not name a type". How can I fix this problem?
#if defined(ARDUINO) && ARDUINO > 18 // Arduino 0019 or later
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDNS.h> //Only needed in Arduino 0022 or earlier
#include <Twitter.h>
byte MACaddress[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte IPaddress[] = { 10, 0, 0, 177 };
Twitter twitter("MY TOKEN HERE");
char msg[] = "Hello, World! I'm Arduino!";
void setup()
{
delay(1000);
Ethernet.begin(MACaddress, IPaddress);
Serial.begin(9600);
Serial.println("connecting ...");
if (twitter.post(msg)) {
int status = twitter.wait();
if (status == 200) {
Serial.println("OK.");
}
else {
Serial.print("failed : code ");
Serial.println(status);
}
}
else {
Serial.println("connection failed.");
}
}
void loop()
{
}
This is a fair question. It looks a lot like the sample code. The first thing I would try is removing the "<<<" and the ">>>" from the constructor?
Twitter twitter("1521141456-FjH4fHVENG3xxxxxxxxxxxxxxxxxx");
If that does not help you could look at your Ethernet.begin .
Ethernet.begin(mac, ip, gateway, subnet);
rather than
Ethernet.begin(mac, ip);
NOTE
You should be careful posting your twitter token id on a forum. I think you should edit your post so as to hide your token.
I am using two libraries for objectiveC-lua bridge.
One is Lua library (with C API) provided by Lua official web page. Since that library
does not provide API to pass objectiveC object to lua, I opt for another library
for this purpose, and Wax seems to be the only option for now.
This program starts when runLua() is called, where it will invoke test.lua
iOS implementation
-(void) runLua{
[self initLua];
[self invokeLua:#"require test"];
}
-(void)initLua{
// initialize Lua and our load our lua file
L = luaL_newstate(); // create a new state structure for the interpreter
luaL_openlibs(L); // load all the standard libraries into the interpreter
lua_settop(L, 0);
initDone = TRUE;
}
-(void) invokeLua:(NSString*)luaSrcStr{
//NSLog(#"%#",luaSrcStr);
if(!initDone){
NSLog(#"inside invokeLua: not yet init");
[self initLua];
}
lua_settop(L, 0);
int ok = luaL_loadstring(L, [luaSrcStr UTF8String]);
if(ok == 0){
lua_getglobal(L,"debug");
lua_getfield(L,-1, "traceback");
lua_remove(L,-2);
lua_insert(L,-2);
ok = lua_pcall(L, 0, 0, -2);
if (ok != 0){
luaL_error(L, "cannot run lua file: %s",
lua_tostring(L, -1));
return;
}
}
test.lua
local testObject = myLib.newiOSObjWithName("TestObject")
testObject:setObjectLength(3.6)
myLib.passTestObjectToC(testObject)
There is no problem in executing 1st and 2nd line, only 3rd line, error occurs.
Error
PANIC: unprotected error in call to Lua API (cannot run lua file: attempt to index a nil
value stack traceback:
[C]: in function 'passTestObjectToC'
...-451C-9F1D-9CE481B4F9A0/test.app/test.lua:6: in main chunk
[C]: in function 'require'
[string "..."]:3: in main chunk)
The error seems to indicate that the function passTestObjectToC is not found in lua, which in this case is not true as the function is registered to lua when luaL_openlibs(L) is called.
My guess, the problem comes where objectiveC object is passed to lua using wax_instance_create(luaState *L, ...). After passing the object, Wax probably has changed the luaState *L that it doesnt remember that passTestObjectToC is already registered.
The C implementation as below.
C implementation
static int newiOSObjWithName(lua_State *L){
NSString *className = [NSString stringWithCString:lua_tostring(L, -1)
encoding:NSUTF8StringEncoding];
className = [className stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:
[[className substringToIndex:1] uppercaseString]];
id classId = [[NSClassFromString(className) alloc] init];
luaopen_wax_instance(L);
wax_instance_create(L, classId, YES);
return 1;
}
static int passTestObjectToC(lua_State *L){
// something to be done here
return 0;
}
static const struct luaL_Reg myLib [] = {
{"newiOSObjWithName", newiOSObjWithName},
{"passTestObjectToC", passTestObjectToC},
{NULL, NULL}
}
int luaopen_mylib (lua_State *L){
luaL_register(L, "myLib", myLib);
return 1;
}
linit.c of Lua Library
static const luaL_Reg lualibs[] = {
{"", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_DBLIBNAME, luaopen_debug},
{"myLib", luaopen_mylib},
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib = lualibs;
for (; lib->func; lib++) {
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
}
Anyone can tell me why there is an error for passTestObjectToC call? What is the reason?
There is no example of Wax implementation for passing iOSObject available. I hv not found it.
So I am not sure if this is the right way to do it. Most examples use Wax to implement iOS classes/functions directly in Lua script instead.
My mistake, there is no problem in the codes above. Function passTestObjectToC is successfully called, the error occurred because of the implementation inside passTestObjectToC and not during the calling of passTestObjectToC.
iOS object is successfully passed from iOS to Lua using Wax as above.
Does MonoTouch have a simple mechanism for retrieving the device serial number (not UDID) of an iOS device? Is there a third-party library which I can use to obtain this?
In case it matters, I'm looking to use this functionality in an in-house application and am not concerned with the App Store approval process.
UPDATE: from iOS 8, we cannot retrieve the serial number of our iDevice.
To retrieve iphone serial number from Monotouch, you can use this technic:
Create a static library .a from XCode that have a function to get serial number
In MonoDevelop, create a binding project to bind you .a library into C# classes/functions (http://docs.xamarin.com/guides/ios/advanced_topics/binding_objective-c_libraries)
In your application, you call this binding library (in step 2).
For detail:
STEP 1. In my library.a, I have a class DeviceInfo, here is the implementation to get Serial number
#import "DeviceInfo.h"
#import <dlfcn.h>
#import <mach/port.h>
#import <mach/kern_return.h>
#implementation DeviceInfo
- (NSString *) serialNumber
{
NSString *serialNumber = nil;
void *IOKit = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);
if (IOKit)
{
mach_port_t *kIOMasterPortDefault = dlsym(IOKit, "kIOMasterPortDefault");
CFMutableDictionaryRef (*IOServiceMatching)(const char *name) = dlsym(IOKit, "IOServiceMatching");
mach_port_t (*IOServiceGetMatchingService)(mach_port_t masterPort, CFDictionaryRef matching) = dlsym(IOKit, "IOServiceGetMatchingService");
CFTypeRef (*IORegistryEntryCreateCFProperty)(mach_port_t entry, CFStringRef key, CFAllocatorRef allocator, uint32_t options) = dlsym(IOKit, "IORegistryEntryCreateCFProperty");
kern_return_t (*IOObjectRelease)(mach_port_t object) = dlsym(IOKit, "IOObjectRelease");
if (kIOMasterPortDefault && IOServiceGetMatchingService && IORegistryEntryCreateCFProperty && IOObjectRelease)
{
mach_port_t platformExpertDevice = IOServiceGetMatchingService(*kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpertDevice)
{
CFTypeRef platformSerialNumber = IORegistryEntryCreateCFProperty(platformExpertDevice, CFSTR("IOPlatformSerialNumber"), kCFAllocatorDefault, 0);
if (CFGetTypeID(platformSerialNumber) == CFStringGetTypeID())
{
serialNumber = [NSString stringWithString:(__bridge NSString*)platformSerialNumber];
CFRelease(platformSerialNumber);
}
IOObjectRelease(platformExpertDevice);
}
}
dlclose(IOKit);
}
return serialNumber;
}
#end
STEP 2. In ApiDefinition.cs of my Binding Library project in Monotouch, I add this binding:
[BaseType (typeof (NSObject))]
public interface DeviceInfo {
[Export ("serialNumber")]
NSString GetSerialNumber ();
}
STEP 3. In my application, I import Reference to Binding library project in step 2, then add
using MyBindingProject;
...
string serialNumber = "";
try {
DeviceInfo nativeDeviceInfo = new DeviceInfo ();
NSString temp = nativeDeviceInfo.GetSerialNumber();
serialNumber = temp.ToString();
} catch (Exception ex) {
Console.WriteLine("Cannot get serial number {0} - {1}",ex.Message, ex.StackTrace);
}
Hope that helps. Don't hesitate if you have any question.