Get ip range with objective C - ios

I do small iPhone app and I need to get IP range and iterate through it with objective C. I can get local IP, netmask. Also I have found on SO solution how to get Broadcast address. But how can I get also Network address? By knowing Network address what is first in the local network and Broadcast address what is last in the local network I would like to iterate all IP from that range. Simply call it and see response. How can I do that?
Solution to get Broadcast from https://stackoverflow.com/a/21077257
#include <net/ethernet.h>
#include <arpa/inet.h>
NSString *localIPAddress = #"192.168.1.10";
NSString *netmaskAddress = #"255.255.192.0";
// Strings to in_addr:
struct in_addr localAddr;
struct in_addr netmaskAddr;
inet_aton([localIPAddress UTF8String], &localAddr);
inet_aton([netmaskAddress UTF8String], &netmaskAddr);
// The broadcast address calculation:
localAddr.s_addr |= ~(netmaskAddr.s_addr);
// in_addr to string:
NSString *broadCastAddress = [NSString stringWithUTF8String:inet_ntoa(localAddr)];
Update: from netmaskAddress I can get number of hosts in the network. I only need to work with IPs. The question now is how can I get next IP from the given? For example I have
NSString *ip = "192.168.1.5"
How can I get "192.168.1.6" with objective C?

I do not recommend do bit operations on this kind of IP's (in_addr) because if you will take a look inside the bytes are reverse ordered.
The code below is printing the device ip, network ip, netmask and broadcast address and all ip's in network range. It might be helpful. Enjoy!
NetworkInformation *network = [[NetworkInformation alloc] init];
NSLog(#"%#", network);
for(NSString *ip in network.ipsInRange){
NSLog(#"ip: %#", ip);
}
NetworkInformation.h
#import <Foundation/Foundation.h>
#interface NetworkInformation : NSObject
#property (nonatomic, retain) NSString *deviceIP;
#property (nonatomic, retain) NSString *netmask;
#property (nonatomic, retain) NSString *address;
#property (nonatomic, retain) NSString *broadcast;
#property (nonatomic, retain) NSArray *ipsInRange;
- (void)updateData;
- (NSString *)description;
#end
NetworkInformation.m
#import "NetworkInformation.h"
#import <arpa/inet.h>
#import <ifaddrs.h>
#implementation NetworkInformation
- (id)init {
self = [super init];
if (self) {
[self updateData];
}
return self;
}
-(void)updateData {
[self updateDataFromWifiNetwork];
self.address = [self getNetworkAddress];
self.ipsInRange = [self getIPsInRange];
}
- (void)updateDataFromWifiNetwork {
self.deviceIP = nil;
self.netmask = nil;
self.broadcast = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0){
temp_addr = interfaces;
while(temp_addr != NULL){
if(temp_addr->ifa_addr->sa_family == AF_INET){
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:#"en0"]){
self.deviceIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
self.netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
self.broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
if(!self.deviceIP || !self.netmask){
NSLog(#"error in updateDataFromWifiNetwork, device ip: %# netmask: %#", self.deviceIP, self.netmask);
}
}
-(NSString*)getNetworkAddress {
if(!self.deviceIP || !self.netmask){
return nil;
}
unsigned int address = [self convertSymbolicIpToNumeric:self.deviceIP];
address &= [self convertSymbolicIpToNumeric:self.netmask];
return [self convertNumericIpToSymbolic:address];
}
-(NSArray*)getIPsInRange {
unsigned int address = [self convertSymbolicIpToNumeric:self.address];
unsigned int netmask = [self convertSymbolicIpToNumeric:self.netmask];
NSMutableArray *result = [[NSMutableArray alloc] init];
int numberOfBits;
for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {
if ((netmask << numberOfBits) == 0){
break;
}
}
int numberOfIPs = 0;
for (int n = 0; n < (32 - numberOfBits); n++) {
numberOfIPs = numberOfIPs << 1;
numberOfIPs = numberOfIPs | 0x01;
}
for (int i = 1; i < (numberOfIPs) && i < numberOfIPs; i++) {
unsigned int ourIP = address + i;
NSString *ip = [self convertNumericIpToSymbolic:ourIP];
[result addObject:ip];
}
return result;
}
-(NSString*)convertNumericIpToSymbolic:(unsigned int)numericIP {
NSMutableString *sb = [NSMutableString string];
for (int shift = 24; shift > 0; shift -= 8) {
[sb appendString:[NSString stringWithFormat:#"%d", (numericIP >> shift) & 0xff]];
[sb appendString:#"."];
}
[sb appendString:[NSString stringWithFormat:#"%d", (numericIP & 0xff)]];
return sb;
}
-(unsigned int)convertSymbolicIpToNumeric:(NSString*)symbolicIP {
NSArray *st = [symbolicIP componentsSeparatedByString: #"."];
if (st.count != 4){
NSLog(#"error in convertSymbolicIpToNumeric, splited string count: %lu", st.count);
return 0;
}
int i = 24;
int ipNumeric = 0;
for (int n = 0; n < st.count; n++) {
int value = [(NSString*)st[n] intValue];
if (value != (value & 0xff)) {
NSLog(#"error in convertSymbolicIpToNumeric, invalid IP address: %#", symbolicIP);
return 0;
}
ipNumeric += value << i;
i -= 8;
}
return ipNumeric;
}
-(NSString*)description {
return [NSString stringWithFormat: #"\nip:%#\nnetmask:%#\nnetwork:%#\nbroadcast:%#", self.deviceIP, self.netmask, self.address, self.broadcast];
}
#end

Related

Why NSString and NSNumber are not released after inserting it into [NSHashTable weakObjectsHashTable]?

I was trying to use NSHashTable to store some object pointers with weak references. During learning, I found that NSString(NSNumber) objects are not released after inserting it into [NSHashTable weakObjectsHashTable]. Any self defined class will work otherwise.
Any idea about why NSString(NSNumber) objects are not released?
#import <Foundation/Foundation.h>
#interface C : NSObject
#property(nonatomic) NSHashTable *hashTable;
#end
#implementation C
- (instancetype)init {
self = [super init];
if (self) {
_hashTable = [NSHashTable weakObjectsHashTable];
}
return self;
}
- (void)addObject:(NSObject *)obj {
[self.hashTable addObject:obj];
}
- (void)printAllObjects {
NSLog(#"Members: %#", [self.hashTable allObjects]);
[[self.hashTable allObjects] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#"%p\n", obj);
}];
}
+ (void)hi:(C *)c {
#autoreleasepool {
NSString *s;
for(int i=0; i<10000; i++) {
s = [[NSString alloc] initWithFormat:#"%d", i];
[c addObject:s];
}
}
}
#end
void hi(C *c) {
NSString *i = #"hi";
NSLog(#"%p", i);
[c addObject:i];
}
int main(int argc, char *argv[]) {
C *c = [[C alloc] init];
#autoreleasepool {
[C hi:c];
}
[c printAllObjects];
}
Xcode Version is 8.1 (8B62) and output is:
2016-12-12 11:16:30.361 0x7fff9106c920
2016-12-12 11:16:30.362 Members: (
""
)
2016-12-12 11:16:30.362 0x7fff9106c920

Apple Pay Integration using Cybersource

I am Integrating Apple Pay Integration using cyberSource in my Application .
what i have done so for .
1- I have created merchant ID
2- I have created test account on http://www.cybersource.com/
3- I have downloaded cybersource SDK for iOS.
4- I have managed to run Demo Application downloaded with SDK.
5- When i run demo App i am getting this error.
"Transaction Details .Accepted: No .Auth Amount: (null) Error: Unknown error"
I have provided my merchant account correctly . There are other fields as well which i am not sure how to get those values
static NSString* kMetadataEncodedValue = #"RklEPUNPTU1PTi5MRy5JTkFQUC5QQVlNRU5U";
static NSString* const kPaymentSolutionDefaultValue = #"001";
static NSString* const kEnvTest = #"test";
static NSString* const kEnvLive = #"live";
static NSString* const kKeyMerchantID = #"merchant_otm_eyebuy_acct";
static NSString* const kKeyMerchantExternalID = #"merchant_otm_eyebuy_acct";
static NSString* const kKeyTransactionKey = #"transactionKey";
static NSString* const kKeyEncryptedBlob = #"encryptedBlob";
static NSString* const kKeyEnv = #"env";
- (IBAction)payButtonTouchDown:(id)sender {
[self.amountTextField resignFirstResponder];
NSString* requestType = [self.requestTypeSelection titleForSegmentAtIndex:self.requestTypeSelection.selectedSegmentIndex];
[self updateStatusMessage:[NSString stringWithFormat:#"Submitting %# request...", requestType]];
self.payButton.enabled = NO;
NSString *amountText = self.amountTextField.text;
NSDecimalNumber *amountValue = [NSDecimalNumber decimalNumberWithString:amountText];
BOOL isDecimal = amountValue!= nil;
if (isDecimal) {
// TODO: Pass in encrypted payment data from PassKit
[self performRequestWithEncryptedPaymentData:self.selectedAccountData[kKeyEncryptedBlob] withPaymentAmount:amountValue];
}
else {
self.payButton.enabled = YES;
self.statusText.text = #"Enter valid Amount";
}
}
- (IBAction)requestTypeSelectionValueChanged:(UISegmentedControl *)sender {
[self updateRequestSelection];
}
-(void) updateRequestSelection {
NSString* requestType = [self.requestTypeSelection titleForSegmentAtIndex:self.requestTypeSelection.selectedSegmentIndex];
[self updateStatusMessage:[NSString stringWithFormat:#"Tap '%#' to %# request.", self.payButton.currentTitle, requestType]];
}
- (void) updateStatusMessage: (NSString*) message
{
self.statusText.text = message;
self.payButton.enabled = YES;
}
- (void)performRequestWithEncryptedPaymentData: (NSString*) encryptedPaymentData withPaymentAmount: (NSDecimalNumber*) paymentAmount
{
VMposItem *item = [[VMposItem alloc] init];
item.name = NSLocalizedString(#"Item no 1", nil);
item.price = paymentAmount;
VMposTransactionObject *transactionObject = [VMposTransactionObject createTransaction:VMPOS_TRANSACTION_PAYMENT];
[transactionObject addItem:item];
[transactionObject calculateTotals];
// TODO: Encrypted Payment is created by client application based
// on specification from SOAP API. The following values are just place holders
VMposEncryptedPayment* payment = [VMposEncryptedPayment new];
payment.encodedData = encryptedPaymentData;
payment.encodedMetadata = kMetadataEncodedValue;
payment.paymentSolution = kPaymentSolutionDefaultValue;
// Purchase details
VMposPurchaseDetails* purchaseDetails = [VMposPurchaseDetails new];
purchaseDetails.partialIndicator = NO;
// Sample Billing information
VMposAddress* billTo = [VMposAddress new];
billTo.firstName = #"John";
billTo.lastName = #"Doe";
billTo.email = #"john.doe#yahoo.com";
billTo.street1 = #"1234 Pine St.";
billTo.city = #"Redmond";
billTo.state = #"WA";
billTo.postalCode = #"98052";
billTo.country = #"US";
// Save transaction information
transactionObject.encryptedPayment = payment;
transactionObject.purchaseDetails = purchaseDetails;
transactionObject.purchaseDetails.commerceIndicator = #"internet";
transactionObject.transactionCode = #"ref_code_12345678";
transactionObject.billTo = billTo;
// Build fingerprint
//--WARNING!----------------
// Finger print generation requires the transaction key. This should
// be done at the server. It is shown here only for Demo purposes.
NSString* merchantID = self.selectedAccountData[kKeyMerchantID];
NSString* fingerprint = [self buildFingerprintWithTransaction:transactionObject withMerchantId:merchantID];
NSLog(#"Fingerprint: %#", fingerprint);
VMposGateway* gateway = [VMposGateway sharedInstance];
[gateway initSessionWithUserName:merchantID withMerchantId:merchantID withFingerprint: fingerprint withDelegate:self];
if (self.selectedAccountData[kKeyEnv] == kEnvLive) {
[VMposSettings sharedInstance].cybsEnvironment = ENV_LIVE;
}
else
{
[VMposSettings sharedInstance].cybsEnvironment = ENV_TEST;
}
if (self.requestTypeSelection.selectedSegmentIndex == 0)
{
[gateway performAuthorizationWithTransaction:transactionObject withDelegate:self];
}
else
{
[gateway performSaleWithTransaction:transactionObject withDelegate:self];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self configureAccounts];
[self updateStatusMessage:[NSString stringWithFormat:#"Tap '%#' to submit a test request.", self.payButton.currentTitle]];
self.amountTextField.keyboardType = UIKeyboardTypeDecimalPad;
self.amountTextField.text = #"1.09";
[self.requestTypeSelection setSelectedSegmentIndex:0];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return self.configuredAccounts.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSDictionary* rowData = self.configuredAccounts[row];
return [NSString stringWithFormat:#"%# (%#)", rowData[kKeyMerchantID], rowData[kKeyEnv]];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
self.selectedAccountData = self.configuredAccounts[row];
}
//! Callback for user session initialization
- (void) didInitUserSession: (VMposUserSession*) paramUserSession withError:(VMposError*)paramError {
}
//! provides feedback from finished authorization transaction request
/*!
\param paramResponseData gateway data retrieved from server (contains information about transaction status)
\param paramError an error if request failed
*/
- (void) authorizationFinishedWithGatewayResponse:(VMposGatewayResponse *)paramResponseData
withError:(VMposError *)paramError {
self.authorized = YES;
[self updateStatusMessageWithResponse: (VMposGatewayResponse *)paramResponseData withError: paramError];
}
//! provides feedback from finished sale request
/*!
\param paramResponseData gateway data retrieved from server (contains information about transaction status)
\param paramError an error if request failed
*/
- (void) saleFinishedWithGatewayResponse:(VMposGatewayResponse *)paramResponseData
withError:(VMposError *)paramError
{
self.authorized = YES;
[self updateStatusMessageWithResponse: (VMposGatewayResponse *)paramResponseData withError: paramError];
}
- (void) updateStatusMessageWithResponse: (VMposGatewayResponse *)paramResponseData withError: (NSError*) paramError
{
NSMutableString* s = [NSMutableString new];
if (paramResponseData)
{
[s appendString: #"\nTransaction Details:"];
[s appendFormat: #"\n * Accepted: %#", paramResponseData.isAccepted ? #"Yes" : #"No"];
[s appendFormat: #"\n * Auth Amount: %#", paramResponseData.authorizedAmount.stringValue];
}
if (paramError)
{
[s appendFormat:#"\nError: %#", paramError.localizedDescription];
}
[self updateStatusMessage:s];
}
/*
----------WARNING!----------------
Finger print generation requires the transaction key. This should
be done at the server. It is shown here only for Demo purposes.
*/
-(NSString*) buildFingerprintWithTransaction: (VMposTransactionObject*) transactionObject withMerchantId: (NSString*) merchantId {
NSDate* dateNow = [NSDate date];
NSString* fingerprintDateString = [MPDemoViewController formatFingerprintDate:dateNow];
NSString* merchantTransKey = self.selectedAccountData[kKeyTransactionKey];
NSString* fgComponents = [NSString stringWithFormat:#"%#%#%#%#%#", [MPDemoViewController stringSha1:merchantTransKey], merchantId, transactionObject.transactionCode, [transactionObject.totalAmount gatewayPriceString], fingerprintDateString];
NSString* hashedFgComponents = [MPDemoViewController stringHmacSha256:fgComponents];
return [NSString stringWithFormat:#"%##%#", hashedFgComponents, fingerprintDateString];
}
+(NSString*) formatFingerprintDate: (NSDate*) date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone* tz = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:tz];
return [dateFormatter stringFromDate:date];
}
+ (NSString *)stringSha1:(NSString *)value
{
const char *cstr = [value cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:value.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
// This is an iOS5-specific method.
// It takes in the data, how much data, and then output format, which in this case is an int array.
CC_SHA1(data.bytes, (uint)data.length, digest);
return [self stringHexEncode:digest withLength:CC_SHA1_DIGEST_LENGTH];
}
+ (NSString *)stringSha256:(NSString *)value
{
const char *cstr = [value cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:value.length];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
// This is an iOS5-specific method.
// It takes in the data, how much data, and then output format, which in this case is an int array.
CC_SHA256(data.bytes, (uint)data.length, digest);
return [self stringHexEncode:digest withLength:CC_SHA256_DIGEST_LENGTH];
}
+ (NSString *)stringHmacSha256:(NSString *)value
{
CCHmacContext ctx;
const char* utf8ValueString = [value UTF8String];
uint8_t hmacData[CC_SHA256_DIGEST_LENGTH];
CCHmacInit(&ctx, kCCHmacAlgSHA256, utf8ValueString, strlen(utf8ValueString));
CCHmacUpdate(&ctx, utf8ValueString, strlen(utf8ValueString));
CCHmacFinal(&ctx, hmacData);
return [self stringHexEncode:hmacData withLength:CC_SHA256_DIGEST_LENGTH];
}
+(NSString*) stringHexEncode: (uint8_t*) data withLength: (NSInteger) dataLength {
NSMutableString* output = [NSMutableString stringWithCapacity:dataLength * 2];
// Parse through the CC_SHA256 results (stored inside of digest[]).
for(int i = 0; i < dataLength; i++) {
[output appendFormat:#"%02x", data[i]];
}
return output;
}
+ (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] ;
}
From where i can get all these values . it will be highly appreciated if some one in list all steps involved in Apple pay integration through CyberSource.
Also Please do not refer me to apple developer as i have read out details about Apple Pay on Apple Developer.

Negative Value data usage on iPhone?

I'm checking my users data consumption using the method below, taken from here. It's working well most of the time, but for some users it's returning a negative value. In other words the WWANReceived is negative.
How can that be? Is there a fix?
+ (NSArray *)getDataCounters {
BOOL success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct if_data *networkStatisc;
int WiFiSent = 0;
int WiFiReceived = 0;
int WWANSent = 0;
int WWANReceived = 0;
NSString *name = [[NSString alloc]init];
// getifmaddrs
success = getifaddrs(&addrs) == 0;
if (success)
{
cursor = addrs;
while (cursor != NULL)
{
name = [NSString stringWithFormat:#"%s",cursor->ifa_name];
// names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
if (cursor->ifa_addr->sa_family == AF_LINK)
{
if ([name hasPrefix:#"en"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WiFiSent += networkStatisc->ifi_obytes;
WiFiReceived += networkStatisc->ifi_ibytes;
}
if ([name hasPrefix:#"pdp_ip"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WWANSent += networkStatisc->ifi_obytes;
WWANReceived += networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil];
}
Maybe you've already solved this I was just testing the same example and came upon this.
You have to change the type from int to long long to handle bigger values. What you're seeing is integer overflow that happens after 2GB of traffic.

How to add sysex data to MusicTrack? (AudioToolbox)

I'm trying to write my little midi sequencer with blackjack and etc but stuck on writing sysex data into MusicTrack. I use following code to insert sysex events
// ---- Some code here --- //
PatternData pattern = { sizeof(PatternData), i, signature.numerator, signature.denominator };
CABarBeatTime beattime = CABarBeatTime((i * signature.numerator * signature.denominator) + 1, 1, 0, SUBBEAT_DIVISOR_DEFAULT);
// Convert beattime to timestamp
if ((MusicSequenceBarBeatTimeToBeats(sequence, &beattime, &timestamp)) != noErr)
{
return status;
}
// Add event
if ((status = MusicTrackNewMIDIRawDataEvent(track, timestamp, (MIDIRawData*)&pattern)) != noErr)
{
return status;
}
// ---- Some code here --- //
PatternData is
typedef struct PatternData
{
UInt32 length; // Struct length
UInt8 index; // Pattern index
UInt8 bars; // Number of bars in patten
UInt8 beats; // Number of beats in pattern
} PatternData;
I did something wrong because after call MusicSequenceFileCreate i get corrupted file.
Does somebody have an example of how to add sysex data to a music track?
Ok. I found a right way, here is it:
UInt8 data[] = { 0xF0, manufacturerId, databyte1, databyte2, databyte3, 0xF7 };
MIDIRawData raw;
memcpy(raw.data, data, 0, sizeof(data));
raw.length = sizeof(data);
if ((status = MusicTrackNewMIDIRawDataEvent(track, timestamp, &raw)) != noErr)
{
return status;
}
Here is an example, how to record normal MIDI and SYSEX messages in a MIDI track and save them in a MIDI file in the shared iTunes folder (set "Application supports iTunes file sharing" to "YES" in .plist):
See specially "calloc" in the code!!
#import "ViewController.h"
#import <CoreMIDI/MIDIServices.h>
#import <CoreMIDI/CoreMIDI.h>
#import "AppDelegate.h"
#include <sys/time.h>
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#end
#implementation ViewController
#synthesize SYSEX_8;
long secTempA = 0;
float secTempB = 0;
long secStartA = 0;
float secStartB = 0;
MusicTimeStamp timeStamp = 0;
MusicSequence recordSequence;
MusicTrack recordTrack;
MusicTimeStamp lenRec = 0;
MIDINoteMessage noteMessage;
MusicTrack track;
NSString *fileNameForSave = #"";
NSString *midiFileWritePath = #"";
NSString *documentsDirectoryPath = #"";
UIAlertView *infoStore;
UIAlertView *infoStoreError;
MIDIRawData *sysexData;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Get documents Directory
// (don't forget the ".plist" entry "Application supports iTunes file sharing YES"
NSArray *pathDocDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectoryPath = [pathDocDir objectAtIndex:0];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)SYSEX_8_touchdown:(id)sender {
NewMusicSequence(&recordSequence);
MusicSequenceNewTrack(recordSequence, &recordTrack);
MusicSequenceSetSequenceType(recordSequence, kMusicSequenceType_Beats);
timeStamp = 0;
struct timeval time;
gettimeofday(&time, NULL);
secStartA = time.tv_sec;
secStartB = time.tv_usec * 0.000001;
noteMessage.channel = 0x90; // Note ON
noteMessage.note = 0x3C;
noteMessage.velocity = 0x7F;
MusicTrackNewMIDINoteEvent(recordTrack, timeStamp, &noteMessage);
NSLog(#"%02x %02x %02x", 0x90, 0x3C, 0x7F);
usleep(10000);
gettimeofday(&time, NULL);
secTempA = time.tv_sec;
secTempB = time.tv_usec * 0.000001;
secTempA = secTempA - secStartA;
secTempB = secTempB - secStartB;
timeStamp = (secTempA + secTempB) * 2;
noteMessage.channel = 0x90; // Note OFF
noteMessage.note = 0x3C;
noteMessage.velocity = 0x00;
MusicTrackNewMIDINoteEvent(recordTrack, timeStamp, &noteMessage);
NSLog(#"%02x %02x %02x", 0x90, 0x3C, 0x00);
usleep(100000);
gettimeofday(&time, NULL);
secTempA = time.tv_sec;
secTempB = time.tv_usec * 0.000001;
secTempA = secTempA - secStartA;
secTempB = secTempB - secStartB;
timeStamp = (secTempA + secTempB) * 2;
Byte datatest[8];
UInt32 theSize = offsetof(MIDIRawData, data[0]) + (sizeof(UInt8) * sizeof(datatest));
sysexData = (MIDIRawData *)calloc(1, theSize);
sysexData->length = sizeof(datatest);
datatest[0] = 0xF0; // Start SYSEX
datatest[1] = 0x26;
datatest[2] = 0x79;
datatest[3] = 0x0E;
datatest[4] = 0x00;
datatest[5] = 0x00;
datatest[6] = 0x00;
datatest[7] = 0xF7; // End SYSEX
for (int j = 0; j < sizeof(datatest); j++) {
sysexData->data[j] = datatest[j];
NSLog(#"%02x", sysexData->data[j]);
}
int status;
if ((status = MusicTrackNewMIDIRawDataEvent(recordTrack, timeStamp, sysexData) != noErr)) {
NSLog(#"error %i", status);
}
else {
[self stopRecording];
}
}
- (void) stopRecording {
CAShow(recordSequence); // To show all MIDI events !!!
UInt32 sz = sizeof(MusicTimeStamp);
lenRec = 0;
MusicSequenceGetIndTrack(recordSequence, 0, &track);
MusicTrackGetProperty(track, kSequenceTrackProperty_TrackLength, &lenRec, &sz);
if (lenRec > 0.1){
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss +zzzz"];
NSDate *startDate = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:startDate];
startDate = [startDate dateByAddingTimeInterval:interval];
// NSLog(#"Date: %#", startDate);
NSString *strDate = [[NSString alloc] initWithFormat:#"%#", startDate];
NSArray *arr = [strDate componentsSeparatedByString:#" "];
NSString *str;
str = [arr objectAtIndex:0];
NSArray *arr_date = [str componentsSeparatedByString:#"-"];
int year = [[arr_date objectAtIndex:0] intValue];
int month = [[arr_date objectAtIndex:1] intValue];
int day = [[arr_date objectAtIndex:2] intValue];
str = [arr objectAtIndex:1];
NSArray *arr_time = [str componentsSeparatedByString:#":"];
int hours = [[arr_time objectAtIndex:0] intValue];
int minutes = [[arr_time objectAtIndex:1] intValue];
int seconds = [[arr_time objectAtIndex:2] intValue];
fileNameForSave = [NSString stringWithFormat:#"%#_%04d%02d%02d_%02d%02d%02d%#", #"$Record", year, month, day, hours, minutes, seconds, #".mid"];
midiFileWritePath = [documentsDirectoryPath stringByAppendingPathComponent:fileNameForSave];
infoStore = [[UIAlertView alloc]initWithTitle: #"Save as MIDI file ?"
message: [NSString stringWithFormat:#"\n%#", fileNameForSave]
delegate: self
cancelButtonTitle: #"YES"
otherButtonTitles: #"NO",nil];
[infoStore show]; // rest siehe unten !!!!!
}
else {
MusicSequenceDisposeTrack(recordSequence, track);
DisposeMusicSequence(recordSequence);
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(int)buttonIndex {
// deletion code here
if (alertView == infoStore) {
if (buttonIndex == 0) {
NSURL *midiURL = [NSURL fileURLWithPath:midiFileWritePath];
OSStatus status = 0;
status = MusicSequenceFileCreate(recordSequence, (__bridge CFURLRef)(midiURL), kMusicSequenceFile_MIDIType, kMusicSequenceFileFlags_EraseFile, 0);
if (status != noErr) {
infoStoreError = [[UIAlertView alloc]initWithTitle: #"Information"
message: [NSString stringWithFormat:#"\nError storing MIDI file in: %#", documentsDirectoryPath]
delegate: self
cancelButtonTitle: nil
otherButtonTitles:#"OK",nil];
[infoStoreError show];
}
}
MusicSequenceDisposeTrack(recordSequence, track);
DisposeMusicSequence(recordSequence);
}
}
#end

Usage of global variables in Objective-C

What is the best practice to use global variables in Objective-C?
Right now I have a class .h/.m with all of the global variables and where common functions is declared like so:
.h
BOOL bOne;
NSInteger iOne;
BOOL bTwo;
BOOL nThreee;
id NilOrValue(id aValue);
BOOL NSStringIsValidEmail(NSString *email);
BOOL NSStringIsValidName(NSString *name);
BOOL NSStringIsVaildUrl ( NSString * candidate );
BOOL NSStringIsValidPhoneNumber( NSString *phoneNumber );
NSString *displayErrorCode( NSError *anError );
NSString *MacAdress ();
NSString* md5( NSString *str );
#define IS_IPHONE ( [[[UIDevice currentDevice] model] isEqualToString:#"iPhone"] )
#define IS_WIDESCREEN (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double) 568) < DBL_EPSILON)
#define IS_IPHONE_5 ( IS_WIDESCREEN )
#define kSettings [NSUserDefaults standardUserDefaults];
#define EMPTYIFNIL(foo) ((foo == nil) ? #"" : foo)
.m
BOOL bOne = NO;
NSInteger iOne = 0;
BOOL bTwo = NO;
BOOL nThreee = NO;
id NilOrValue(id aValue) {
if ((NSNull *)aValue == [NSNull null]) {
return nil;
}
else {
return aValue;
}
}
NSString* md5( NSString *str )
{
// Create pointer to the string as UTF8
const char *ptr = [str UTF8String];
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(ptr, (CC_LONG)strlen(ptr), md5Buffer);
// Convert MD5 value in the buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x",md5Buffer[i]];
return output;
}
BOOL NSStringIsVaildUrl (NSString * candidate) {
NSString *urlRegEx =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
BOOL NSStringIsValidEmail(NSString *email) {
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if (email.length == 0) {
return YES;
}else {
if (![emailTest evaluateWithObject:email]) {
return NO;
}else {
return YES;
}
}
}
BOOL NSStringIsValidName(NSString *name) {
NSString *nameRegex = #"^([a-zA-Z'-]+)$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", nameRegex];
if (name.length == 0) {
return YES;
}else {
if (![nameTest evaluateWithObject:name]) {
return NO;
} else {
return YES;
}
}
}
BOOL NSStringIsValidPhoneNumber(NSString *phoneNumber) {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSRange inputRange = NSMakeRange(0, [phoneNumber length]);
NSArray *matches = [detector matchesInString:phoneNumber options:0 range:inputRange];
// no match at all
if ([matches count] == 0) {
return NO;
}
// found match but we need to check if it matched the whole string
NSTextCheckingResult *result = (NSTextCheckingResult *)[matches objectAtIndex:0];
if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) {
// it matched the whole string
return YES;
}
else {
// it only matched partial string
return NO;
}
}
NSString *MacAdress () {
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = #"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = #"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = #"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = #"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(#"Error: %#", errorFlag);
free(msgBuffer);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(#"Mac Address: %#", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
Is this a bad solution? If yes how would I manage to use my global variables in the best way?
Global variable always cause problem but in some scenario it is useful there are two type global variable we required one are constant second are those could change there value...
the recommendation is to create immutable global variables instead of in-line string constants (hard to refactor and no compile-time checking) or #defines (no compile-time checking). Here's how you might do so...
in MyConstants.h:
extern NSString * const MyStringConstant;
in MyConstants.m:
NSString * const MyStringConstant = #"MyString";
then in any other .m file:
#import "MyConstants.h"
...
[someObject someMethodTakingAString:MyStringConstant];
...
This way, you gain compile-time checking that you haven't mis-spelled a string constant, you can check for pointer equality rather than string equality[1] in comparing your constants, and debugging is easier, since the constants have a run-time string value.
for mutable variables the safe way is adopting the singalton pattern
#interface VariableStore : NSObject
{
// Place any "global" variables here
}
// message from which our instance is obtained
+ (VariableStore *)sharedInstance;
#end
#implementation VariableStore
+ (VariableStore *)sharedInstance
{
// the instance of this class is stored here
static VariableStore *myInstance = nil;
// check to see if an instance already exists
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
// initialize variables here
}
// return the instance of this class
return myInstance;
}
#end

Resources