Can we send NSString Value between devices connected via bluetooth, Using Game Center - nsstring

Can we send NSString Value between devices connected via Bluetooth, using Game Center?
Here is some part of my code:
typedef enum {
messageType1 = 0;
messageType2 = 1;
}
messageType;
typedef struct {
MessageType messageType;
NSString *myName;
} MyMessage;
And In my Class I have this method to send the message:
MyMessage myMessage;
myMessage.messageType = messageType2;
myMessage.myName = #"ABCDEFGH";
NSData *data = [NSData dataWithBytes:&myMessage length:sizeof(MyMessage)];
[self sendDataToAllPeers:data withDataMode:GKSendDataReliable error:error];
to receive data I have method:
-(void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession: (GKSession *)session context:(void *)context{
MyMessage myMessage = *((MyMessage *) [data bytes]);
type = myMessage.messageType;
name = myMessage.myName;
}
Question: How can I get myName ? (I am able to get MessageType)

Send NSData as Archived NSArray:
NSArray *array = [[NSArray alloc] initWithObjects:myMessage.messageType, myMessage.myName, nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
[self sendDataToAllPeers:data];
Receive NSData and Unarchive to NSArray:
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData: data];
type = [array objectAtIndex:0];
name = [array objectAtIndex:1];

Related

How to get a video PHAsset disk file size?

I'm trying to determine the file size on disk of a PHAsset video.
The following code is returning am error "The file “IMG_0188.mov” couldn’t be opened because you don’t have permission to view it."
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
videoURL = [(AVURLAsset*)avAsset URL];
NSNumber *videoDiskFileSize;
NSError *error;
[videoURL getResourceValue:&videoDiskFileSize forKey:NSURLFileSizeKey error:&error];
if(error){
NSLog(#"ERROR %#", error.localizedDescription);
}
NSLog(#"size is %f",[videoDiskFileSize floatValue]/(1024.0*1024.0));
}];
Here's the correct way to do it.
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
options.version = PHVideoRequestOptionsVersionOriginal;
[[PHImageManager defaultManager] requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetHighestQuality resultHandler:^(AVAssetExportSession *exportSession, NSDictionary *info) {
CMTime videoDuration = CMTimeMultiplyByFloat64(exportSession.asset.duration, 1);
exportSession.timeRange = CMTimeRangeMake(kCMTimeZero, videoDuration);
NSLog(#"Byyte size = %lld", exportSession.estimatedOutputFileLength);
videoSize = exportSession.estimatedOutputFileLength;
}];

Add contact to Address Book Button

I'm doing and App in IOS and I want to add a Button that when people clik it it automatically add the contact (name, number and Picture) in the phone contact list
the contact name is Clinica Lo Curro and phone No. is 6003667800
Someone can please help me with the code please?
regards,
Eugenio Durán
Add AddressBook.framework and AddressBookUI.framework from Build Phase,Link Binary with Libraries.
And Import AddressBookUI to your header File as displayed below.
#import <AddressBookUI/AddressBookUI.h>
Include delegate ABPeoplePickerNavigationControllerDelegate to header file.
and Call The following method to add Contact.
-(IBAction)addContact:(id)sender
{
ABPeoplePickerNavigationController *peoplePicker=[[ABPeoplePickerNavigationController alloc] init];
ABAddressBookRef addressBook = [peoplePicker addressBook];
// create person record
ABRecordRef person = ABPersonCreate();
// set name and other string values
UIImage *personImage = [UIImage imageNamed:#"cinema.png"];
NSData *dataRef = UIImagePNGRepresentation(personImage);
NSString *firstName=#"AKASH";
NSString *lastName=#"MALHOTRA";
NSString *organization=#"Aua Comp Pvt Ltd.";
NSString *jobTitle=#"iPhone App Developer";
NSString *departMent=#"Mobile Division";
NSString *webURL=#"http://www.google.com";
NSString *personEmail=#"goel.anjan#gmail.com";
NSString *phoneNo=#"9856756445 or 7656876765 or 8976566775";
NSString *personNote=#"I am just a kid";
NSString *addressOne=#"HN-23,Sector-2,Chandigarh";
NSString *addressTwo=#"AL-19,Sector-5,SaltLake";
NSString *cityName=#"Kolkata";
NSString *stateName=#"West Bengal";
NSString *pinCode=#"700091";
NSString *country=#"India";
CFErrorRef cfError=nil;
ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef)organization, NULL);
if (firstName) {
ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridge CFTypeRef)(firstName) , nil);
}
if (lastName) {
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFTypeRef)(lastName) , nil);
}
if (jobTitle) {
ABRecordSetValue(person, kABPersonJobTitleProperty,(__bridge CFTypeRef)(jobTitle), nil);
}
if (departMent) {
ABRecordSetValue(person, kABPersonDepartmentProperty,(__bridge CFTypeRef)(departMent), nil);
}
if (personNote) {
ABRecordSetValue(person, kABPersonNoteProperty, (__bridge CFTypeRef)(personNote), nil);
}
if (dataRef) {
ABPersonSetImageData(person, (__bridge CFDataRef)dataRef,&cfError);
}
if (webURL)
{
ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) webURL, kABPersonHomePageLabel, NULL);
ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil);
CFRelease(urlMultiValue);
}
if (personEmail)
{
ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) personEmail, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
CFRelease(emailMultiValue);
}
if (phoneNo)
{
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
NSArray *venuePhoneNumbers = [phoneNo componentsSeparatedByString:#" or "];
for (NSString *venuePhoneNumberString in venuePhoneNumbers)
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) venuePhoneNumberString, kABPersonPhoneMainLabel, NULL);
ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
CFRelease(phoneNumberMultiValue);
}
// add address
ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
if (addressOne)
{
if (addressTwo)
addressDictionary[(NSString *) kABPersonAddressStreetKey] = [NSString stringWithFormat:#"%#\n%#", addressOne, addressTwo];
else
addressDictionary[(NSString *) kABPersonAddressStreetKey] = addressOne;
}
if (cityName)
addressDictionary[(NSString *)kABPersonAddressCityKey] = cityName;
if (stateName)
addressDictionary[(NSString *)kABPersonAddressStateKey] = stateName;
if (pinCode)
addressDictionary[(NSString *)kABPersonAddressZIPKey] = pinCode;
if (country)
addressDictionary[(NSString *)kABPersonAddressCountryKey] = country;
ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL);
CFRelease(multiAddress);
//Add person Object to addressbook Object.
ABAddressBookAddRecord(addressBook, person, &cfError);
if (ABAddressBookSave(addressBook, nil)) {
NSLog(#"\nPerson Saved successfuly");
} else {
NSLog(#"\n Error Saving person to AddressBook");
}
}

How to store server authentification in source code

In my app I'm doing various request on server API. When I'm doing those requests, part of my requester class is:
NSString *authString = [[[NSString stringWithFormat:#"serverUsername:serverPass"]dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *verifString = [NSString stringWithFormat:#"Basic %#",authString];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *myRequestData = [NSData dataWithBytes:[ms UTF8String] length:[ms length]];
[request setHTTPBody:myRequestData];
I'm not including all of source code, but then I have another strings, that I don't want to be visible in source code (fingerprints etc).
I was searching for code obfuscating, but to no success. Is there any way, to prevent my credential strings to be visible in x-code?
I think the best way is to store it in a plist file.
- (NSString *)saveRecommendUserData {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Userdata.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Userdata" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath: path error:&error];
}
return path;
}

Retrieving data from a plist

`Okay so I am trying to pull questions and possible answers from a plist file I have created
<key>Question1</key>
<string></string>
<key>Answer1</key>
<array/>
<key>4</key>
<string>A</string>
<key>2</key>
<string>B</string>
<key>3</key>
<string>C</string>
So I have tried to do this in code from looking a various tutorials, I am only new to this so I know I have it all wrong
so then I want to place the question in an label created in the storyboard and the same with the possible answers????
`
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *listPath = [[self docDir]stringByAppendingPathComponent:#"work.plist"];
if (![[NSFileManager defaultManager]fileExistsAtPath:listPath]) {
[[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle]pathForResource:#"work" ofType:#"plist"]toPath:listPath error:nil];
}
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:listPath];NSLog(#"count: %i", [array count]);
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
propertyListFromData:#"work.plist";
self.firstQuestion = [temp objectForKey:#"Question1"];
self.firstanswer = [NSMutableArray arrayWithArray:[temp objectForKey:#"Answer"]];`
TRY this too.
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [path objectAtIndex:0];
NSString *plistpath = [documentsPath stringByAppendingPathComponent:#"question.plist"];
NSMutableArray *savedStock = [[NSMutableArray alloc] initWithContentsOfFile:plistFilePath];
for (int i=0; i<[savedStock count]; i++)
{
[A-array addObject:[[savedStock objectAtIndex:i] valueForKey:#"A"]];
[B-array addObject:[[savedStock objectAtIndex:i] valueForKey:#"B"]];
}

remember user selected folder and reopen it by NSOpenPanel under Sandbox

Apple review require my app to remember the folder that user selected last time. But I can not make it under Sandbox. the -setDirectoryURL seems not working under Sandbox.
What should I do? Thank you for your help!
// read string saveFolder from NSUserDefaults
NSOpenPanel * myPanel = [NSOpenPanel openPanel];
[myPanel setTitle:#"Select Output Folder"];
[myPanel setCanChooseDirectories:YES];
[myPanel setCanCreateDirectories:YES];
[myPanel setAllowsMultipleSelection:NO];
[myPanel setCanChooseFiles:NO];
NSLog(#"before openpanel:folder=%#",saveFolder); // <== return normal
[myPanel setDirectoryURL:[NSURL URLWithString:saveFolder.stringValue]];
NSLog(#"readback:folder=%#",[[myPanel URL] path]); // <== return nil here
if ([myPanel runModal] == NSOKButton)
{
//
saveFolder = [[myPanel URL] path]];
// then save the saveFolder string to NSUserDefaults
//
}
it seems we should add and use this entitlement:
com.apple.security.files.bookmarks.app-scope
SAVE THE URL:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSError *error = nil;
NSData *bookmarkData = [[myPanel URL] bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error];
if (!error)
{
[defaults setObject:bookmarkData forKey:#"iData"];
[defaults synchronize];
}
READ BACK:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
bookmarkFileURL = nil;
NSData *bookmarkData = [defaults objectForKey:#"iData"];
if (bookmarkData != nil)
{
NSError *error=nil;
bookmarkFileURL = [NSURL URLByResolvingBookmarkData:bookmarkData options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:&error];
if (error != nil) bookmarkFileURL = nil;
}
if (bookmarkFileURL)
{
[bookmarkFileURL startAccessingSecurityScopedResource];
}
//
//
[bookmarkFileURL stopAccessingSecurityScopedResource];

Resources