Below is my code and I am trying to get signal strength through status bar.
UIApplication *app = [UIApplication sharedApplication];
NSArray *subviews = [[[app valueForKey:#"statusBar"] valueForKey:#"foregroundView"] subviews];
Crash occurred on (iOS 11, Xcode 9, iPhone X):-
[UIStatusBar_Modern valueForUndefinedKey:]: this class is not key value coding-compliant for the key foregroundView
you can use this
NSArray *subviews = nil;
id statusBar = [[UIApplication sharedApplication] valueForKey:#"statusBar"];
if ([statusBar isKindOfClass:NSClassFromString(#"UIStatusBar_Modern")]) {
subviews = [[[statusBar valueForKey:#"statusBar"] valueForKey:#"foregroundView"] subviews];
} else {
subviews = [[statusBar valueForKey:#"foregroundView"] subviews];
}
Use This:
- (NSString*)newtworkType {
NSArray *subviews = nil;
id statusBar = [[UIApplication sharedApplication] valueForKey:#"statusBar"];
if ([statusBar isKindOfClass:NSClassFromString(#"UIStatusBar_Modern")]) {
subviews = [[[statusBar valueForKey:#"statusBar"] valueForKey:#"foregroundView"] subviews];
} else {
subviews = [[statusBar valueForKey:#"foregroundView"] subviews];
}
NSNumber *dataNetworkItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(#"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
switch ([[dataNetworkItemView valueForKey:#"dataNetworkType"]integerValue]) {
case 0:
return #"No wifi or cellular";
break;
case 1:
return #"2G";
break;
case 2:
return #"3G";
break;
case 3:
return #"4G";
break;
case 4:
return #"LTE";
break;
case 5:
return #"WIFI";
break;
default:
break;
}
return #"";
}
Related
i have an error in c# of NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
I found this post in the link below but i didn't understand the solution
SimpleJSON returns null when handling a call from Postmen
Can any one explain it for me, please?
the error is :
NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
SimpleJSON.JSON.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:1363)
Control.Update () (at Assets/Control.cs:123)
knowing that i'm sending json data using websocket and i'm receiving it in the console unity. i use simpleJSON script to deserialize the data.
here where the error is provided in line JSONNode root = JSON.Parse(last_message); :
private void Update()
{
if (ws == null)
{
return;
}
List<GameObject> object_to_keep = new List<GameObject>();
JSONNode root = JSON.Parse(last_message);
JSONNode Face = root["streams"][0]["objects"][0];
{
int id = Face["mono"]["id"].AsInt;
JSONNode position = Face["mono"]["position"];
Vector3 pos = new Vector3(position["x"].AsFloat, position["y"].AsFloat, position["z"].AsFloat);
GameObject mono = GetMonoObject();
WintualFaceController win_controller = mono.GetComponent<WintualFaceController>();
win_controller.face_id = id;
if(mono)
{
mono.transform.localPosition = pos;
object_to_keep.Add(mono);
}
else
print("Mono not found");
}
}
The error in SImpleJSON script wan in line: while (i < aJSON.Length)
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
this is my json:
{
"cmd": "data",
"frame_time": "2021-06-30T09:04:16.464836+00:00",
"start_time": "2021-06-30T07:51:33.452079+00:00",
"streams": [
{
"name": "usb-0001:012.0-3",
"objects": [
{
"name": "face",
"mono": {
"id": "190",
"position": {
"x": "-0.012259",
"y": "0.059731",
"z": "0.707695"
}
},
"multi": [
{
"id": "190",
"position": {
"x": "-0.012263",
"y": "0.059753",
"z": "0.707151"
}
}
]
}
]
}
]
}
Please forgive my noob-ness.
So, i figured out how to create two separate switch loops, in order to access two separate values. My trouble now, is that I don't know how to write a function that would allow me to concatenate the results of the two switch values.
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change',
setWeather);
document.getElementById('dance').addEventListener('change',
setDance);
function setWeather() {
var choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
}
}
function setDance() {
var art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
}
}
function result() {
weatherVal = weather.value;
danceVal = dance.value;
para.textContent = weatherVal + danceVal;
}
I tried to use the above code "function result()" to write the function to create the concatenation, but no success. I feel like the answer is right in front of me, but I'm just not quite sure what's going on.
You could make choice and art global variables and then use them in result like this:
var select = document.getElementById('weather');
var para = document.getElementById('alf');
var door = document.getElementById('dance');
var mort = document.getElementById('tim');
document.getElementById('weather').addEventListener('change', setWeather);
document.getElementById('dance').addEventListener('change', setDance);
var choice;
var art;
function setWeather() {
choice = this.value;
switch(choice) {
case 'sunny':
para.textContent = "fly me to the Moon";
break;
case 'rainy':
para.textContent = "let me sail amongst the stars";
break;
case 'snowy':
para.textContent = "life on Jupiter and Mars";
break;
default:
para.textContent = "";
break;
}
}
function setDance() {
art = this.value;
switch(art) {
case 'hail':
mort.textContent = "in other words";
break;
case 'rail':
mort.textContent = "darling kiss me";
break;
case 'cat':
mort.textContent = "please be true";
break;
default:
mort.textContent = "";
break;
}
}
function result() {
para.textContent = choice + art;
}
OK, I'm using Core Bluetooth to connect my i-Pad to another BLE sensor.
I scan and detect it easily but when I want to establish a connection, the "did connect peripheral" method is only called during 30 sec as if I've called a disconnection...
And this result stay the same even I select or deselect "App Communicates using CoreBluetooth" in Required background mode.
- (id) init
{
self = [super init];
if (self)
{
pendingInit = YES;
centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
foundPeripherals = [[NSMutableArray alloc] init];
connectedServices = [[NSMutableArray alloc] init];
}
return self;
}
- (void) centralManagerDidUpdateState:(CBCentralManager *)central
{
static CBCentralManagerState previousState = -1;
switch ([centralManager state])
{
case CBCentralManagerStateUnsupported:
{
NSLog(#"NSCentralManager State Unsupported...");
break;
}
case CBCentralManagerStatePoweredOff:
{
NSLog(#"NSCentralManager State Powered OFF");
[self clearDevices];
[discoverPeripheralDelegate discoveryDidRefresh];
if (previousState != -1)
{
[discoverPeripheralDelegate discoveryStatePoweredOff];
}
break;
}
case CBCentralManagerStateUnauthorized:
{
NSLog(#"NSCentralManager State Unauthorized: the application is not allowed");
break;
}
case CBCentralManagerStateUnknown:
{
NSLog(#"NSCentralManager state unknown... Bad News...");
break;
}
case CBCentralManagerStatePoweredOn:
{
NSLog(#"NSCentralManager State Powered ON!");
pendingInit = NO;
[self loadSavedDevices];
[centralManager retrieveConnectedPeripherals];
[discoverPeripheralDelegate discoveryDidRefresh];
break;
}
case CBCentralManagerStateResetting:
{
NSLog(#"CBCentralManager State Resetting");
[self clearDevices];
[discoverPeripheralDelegate discoveryDidRefresh];
[peripheralDelegate alarmServiceDidReset];
pendingInit = YES;
break;
}
}
previousState = [centralManager state];
}
- (void) loadSavedDevices
{
storedDevices = [[NSArray alloc] initWithObjects:kPressureServiceUUIDString, nil];
for (id deviceUUIDString in storedDevices) {
if (![deviceUUIDString isKindOfClass:[NSString class]])
continue;
CFUUIDRef uuid = CFUUIDCreateFromString(NULL, (CFStringRef)deviceUUIDString);
if (!uuid)
continue;
storedUUIDs = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"StoredUUIDS"]];
for (int i = 0; i < storedUUIDs.count; i++) {
NSArray * tempStoredUUIDs = storedUUIDs[i];
storedUUIDs[i] = [tempStoredUUIDs mutableCopy];
}
[centralManager scanForPeripheralsWithServices:nil options:nil];
storedUUIDs = [[NSMutableArray alloc] init];
[[NSUserDefaults standardUserDefaults] setObject:storedUUIDs forKey:#"StoredUUIDS"];
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSString * finaluuids = [NSString stringWithFormat:#"%#",peripheral.UUID];
if (storedUUIDs.count == 0)
{
storedUUIDs = [[NSMutableArray alloc] initWithObjects:finaluuids, nil];
[centralManager stopScan];
[centralManager connectPeripheral:peripheral options:nil];
}
}
- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(#"connected");
}
Here is my console. I don't have any warning, any error or deallocating just:
2013-05-14 09:21:14.925 PRESSURE[262:907] connected
2013-05-14 09:21:14.927 PRESSURE[262:907] Service (Sensor) connected
2013-05-14 09:21:44.994 PRESSURE[262:907] Service (Sensor) disconnected
How can I avoid my peripheral disconnected immediately after connection please?
It drives me crazy!
You have to do [peripheral retain] on didDiscoverPeripheral or put it into the retain property.
It is released right after the connect by BLE framework.
This may be a strange problem and I hope someone has had it before.
I added a SegmentControl to my TableView using this code:
UIView *headerView = [[UIView alloc] init ];
[headerView addSubview:resultsSegment];
self.tableView.tableHeaderView = headerView;
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
With help from these forums the first three lines made the Segment part of the TableView Header so that it stayed in place for scrolling. Great.
However, that disabled the ability to click on the SegmentControl.
Adding the last line made that possible again.
The SegmentControl performs great UNTIL scrolling, then it becomes really unresponsive. It doesn't throw up any errors and it does eventually accept a press from the finger, but you have to tap it 5/6 times before it switches.
If anyone can shed some light on this that would be amazing
Any extra information you need I'll be happy to provide!
EDIT ----
ViewController.h
#interface StdTCPTestViewController : UIViewController <UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate> {
NSTimer *Timer;
}
#property (nonatomic, strong) NSString *typeOfTest;
#property (nonatomic, strong) NSString *testLocation;
#property (nonatomic, strong) NSString *statusText;
#property (nonatomic, strong) NSString *showResultType;
#property (nonatomic, assign) NSInteger *progressInt;
#property (nonatomic, assign) NSString *testDirection;
#property (strong, nonatomic) IBOutlet UITextView *textView;
#property (strong, nonatomic) IBOutlet UIProgressView *testProgressBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSArray *ResultTitles;
#property (nonatomic, retain) NSMutableArray *downloadResults;
#property (nonatomic, retain) NSMutableArray *uploadResults;
#property (strong, nonatomic) IBOutlet UISegmentedControl *resultsSegment;
- (IBAction)resultsSwitch:(id)sender;
Select areas of ViewController.m
- (void)viewDidLoad
{
[resultsSegment setTitle:#"Download" forSegmentAtIndex:0]; // Sets the title for the 1st segment button
[resultsSegment setTitle:#"Upload" forSegmentAtIndex:1]; // Sets the title for the 2nd segment button
[super viewDidLoad];
// UIView *headerView = [[UIView alloc] init ];
// [headerView addSubview:resultsSegment];
// self.tableView.tableHeaderView = headerView;
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
[self APISimpleDemo];
self.navigationItem.title = typeOfTest; // Set viewcontroller title to the type of test it is
}
- (IBAction)resultsSwitch:(id)sender {
if([sender selectedSegmentIndex] == 0){
showResultType = #"download";
[self.tableView reloadData];
}
else {
showResultType = #"upload";
[self.tableView reloadData];
}
}
#pragma mark Table Definitions
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; // Default is 1 if not implemented
{
return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return #"";
break;
case 1:
return #"";
break;
case 2:
return #"";
break;
default:
return #"Section Count Error";
break;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
return 35;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return 10;
break;
case 1:
return 22;
break;
case 2:
return 0;
break;
default:
return 22;
break;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
switch (section) {
case 0:
return 3;
break;
case 1:
return 0;
break;
case 2:
return [ResultTitles count];
break;
default:
return 0;
break;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *serverLoc = [tableView dequeueReusableCellWithIdentifier:#"speedCell"];
switch (indexPath.section) {
case 0:
switch (indexPath.row) {
case 0:
serverLoc.textLabel.text = #"Test location:";
serverLoc.detailTextLabel.text = testLocation;
break;
case 1:
serverLoc.textLabel.text = #"Status:";
serverLoc.detailTextLabel.text = statusText;
break;
case 2:
serverLoc.textLabel.text = #"Progress";
serverLoc.detailTextLabel.text = [NSString stringWithFormat:#"%ld%%", (long)progressInt];
break;
}
break;
case 2:
if ([showResultType isEqual:#"download"]) {
serverLoc.textLabel.text = [self.ResultTitles objectAtIndex:indexPath.row];
serverLoc.detailTextLabel.text = [self.downloadResults objectAtIndex:indexPath.row];
break;
}
else {
serverLoc.textLabel.text = [self.ResultTitles objectAtIndex:indexPath.row];
serverLoc.detailTextLabel.text = [self.uploadResults objectAtIndex:indexPath.row];
break;
}
break;
default:
break;
}
return serverLoc;
}
The likely problem here is that you have a single segmentControl but you added it as a subview to both the tableHeaderView and the tableView.
I solved the problem of an unresponsive SegmentControl upon scrolling by moving the code below from the viewDidLoad method to the titleForHeaderInSection
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
It now looks like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
{
switch (section) {
case 0:
return #"";
break;
case 1:
resultsSegment.frame = CGRectMake(45, 123, 250, 40);
[self.tableView addSubview:resultsSegment];
return #"";
break;
case 2:
return #"";
break;
default:
return #"Section Count Error";
break;
}
}
I am using SDL in C, and I'm trying to make a character move on the screen when a key is pressed, and stop when it is released, but it seems as if the KEYUP event is triggering when the key is still being held down. If I remove the KEYUP section in pressed(), the characters will slide across the screen, but obviously won't stop on their own. If I leave the KEYUP section in, I have to press the key repeatedly to move them across the screen.
Any idea what I'm doing wrong?
Here's what I have:
...
int done = 0;
while (done==0)
{
pressed();
if (kenter == 1)
{
state = 1;
subscreen();
}
if (kescape == 1)
{
done = 1;
}
if (kup == 1)
{
playery += -2;
}
if (kdown == 1)
{
playery += 2;
}
if (kright == 1)
{
playerx += 2;
}
if (kleft == 1)
{
playerx += - 2;
}
...
int pressed ()
{
SDL_Event keyevent;
while (SDL_PollEvent(&keyevent))
{
switch(keyevent.type)
{
case SDL_KEYDOWN:
switch(keyevent.key.keysym.sym)
{
case SDLK_RETURN:
{
kenter = 1;
break;
}
case SDLK_ESCAPE:
{
kescape = 1;
break;
}
case SDLK_a:
{
ka = 1;
break;
}
case SDLK_s:
{
ks = 1;
break;
}
case SDLK_UP:
{
kup = 1;
break;
}
case SDLK_DOWN:
{
kdown = 1;
break;
}
case SDLK_RIGHT:
{
kright = 1;
break;
}
case SDLK_LEFT:
{
kleft = 1;
break;
}
default:
break;
}
}
switch(keyevent.type)
{
case SDL_KEYUP:
switch(keyevent.key.keysym.sym)
{
case SDLK_RETURN:
{
kenter = 0;
break;
}
case SDLK_ESCAPE:
{
kescape = 0;
break;
}
case SDLK_a:
{
ka = 0;
break;
}
case SDLK_s:
{
ks = 0;
break;
}
case SDLK_UP:
{
kup = 0;
break;
}
case SDLK_DOWN:
{
kdown = 0;
break;
}
case SDLK_RIGHT:
{
kright = 0;
break;
}
case SDLK_LEFT:
{
kleft = 0;
break;
}
default:
break;
}
}
}
return 0;
}
I think your switch statements are broken.
Use this less confusing way
int pressed ()
{
SDL_Event event;
while(SDL_PollEvent(&event) )
{
if(event.type == SDLK_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_RETURN:
doStuff = 1
break;
default:
break;
}
}
if(event.type == SDLK_KEYUP)
{
switch(event.key.keysym.sym)
{
case SDLK_RETURN:
doStuff = 0;
break;
default:
break;
}
}
}
}
Also important:
SDL Tutorials: Practical Keyboard Input
Oh and avoid using global variables!
Your use of two switch statements is odd and confusing, you should probably fix that.
The issues you're seeing are likely due to keyboard repeat, see the SDL_EnableKeyRepeat() call for how to disable it.
don't use switch. I experienced same thing, but I resolved into using 'if' like this. Maybe switch has 'else if'.
if(event.type == SDL_KEYDOWN){
....
}
if(event.type == SDL_KEYUP){
....
}