I am working on an iphone application which need to encode and decode a string,so I code a small script on obj-c to test my code. This is my code which I am using to test:
this code block is not work, the string AwEMT... is a encoded string by dataUsingEncoding:NSUTF8StringEncoding and base64EncodedStringWithOptions:0, just like the working code block but when i decode it is not work and return null
int main (int argc, const char * argv[]) {
NSData *decodedData1 = [[NSData alloc] initWithBase64EncodedString:#"AwEMTqu5FyZFurKQ7givyJEUruVaMg8TBWU8yyMbP2exbOQW9BgDFwxdoD6cuVb4/fR/Jb7J9uryofUAJi1QVDOwl4dzEj+8JzKHS9/zCmryKa3qN5RUCqSrJ//5gTG7b17mfGEqiObZ7a6xJatyfjRJ42+KW1xSH8SSZlnyk5LvtMuSjYRX18NxXCA9E4dmY2po6ehr8cy+UEm9qcjJZ9d6X7z+xubzy/XYv9aPYvxwBe7ZK/kXLEnt2vtafygag/msDuSnLk43wzhAnNnl4YwxFPsx8uZHpsxwBZEvG7wS+YpqhKIZQF9yBqPFkOQXaa55r6p4uChCoVShKGXq4GZtUf6TwF0S2zmlFCpEImonEJa8IIAAhEuU8OTwPCHFga3DhWpXGiWXxtNpCSFlLzXsoPFgYN2OFkf9TH4fIVHAiOm2Xl8SkbXZ/TBTGNevaJNHAEjg+YZmVwnQcCOvcoRdJhx+2ylDdQOswFTsIbkKRARlfHbz4LWqJNW9YTeA21m26dnvCkNWe+tG64j2gse36r2zwya3ULN63AGXtNT8+A==" options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData1 encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedData1 );
return 0;
}
And this is working code block, I encode the "Developer" string the same way as encoded string: "AwEMT.... But the encoded string from "Developer" can eassily decode by these code.
int main (int argc, const char * argv[]) {
NSString *myString = #"Developer";
NSData *myData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [myData base64EncodedStringWithOptions:0];
NSLog(#"%#", base64String);
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"%#", decodedString);
return 0;
}
Anyone know what I have done wrong on this? please point me out
Related
I am trying to write main array in a file and this main array contain sub array . Now whenever I write main array the sub array get overwritten .
Below is my code.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool {
char fname[10];
printf("Type your first name:\n");
scanf("%s",fname);
NSString *firstname = [[NSString alloc] init];
firstname = [NSString stringWithUTF8String:fname];
char lname[10];
printf("Type your last name:\n");
scanf("%s",lname);
NSString *lastname = [[NSString alloc] init];
lastname = [NSString stringWithUTF8String:lname];
long mnumber = 0;
printf("Enter your register mobile number:\n");
scanf("%ld",&mnumber);
NSNumber *mobilenumber = [NSNumber numberWithLong:mnumber];
long anumber = 0;
printf("Enter your account number:\n");
scanf("%ld",&anumber);
NSNumber *accountnumber = [NSNumber numberWithLong:anumber];
NSURL *docdir = [[NSFileManager defaultManager] URLForDirectory:NSDesktopDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSURL *filepath = [docdir URLByAppendingPathComponent:#"Dexter_apps/filetesting/data.plist"];
NSArray *data = #[firstname,lastname,mobilenumber,accountnumber];
NSMutableArray *mainarray = [[NSMutableArray alloc]init];
mainarray = #[data];
[mainarray writeToURL:filepath atomically:NO];
}
return 0;
}
So I have this code that returns the current safari tab's URL
int main(int argc, const char * argv[]) {
NSAppleScript *script= [[NSAppleScript alloc] initWithSource:#"tell application \"Safari\" to return URL of front document as string"];
NSDictionary *scriptError = nil;
NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
if(scriptError) {
NSLog(#"Error: %#",scriptError);
} else {
NSAppleEventDescriptor *unicode = [descriptor coerceToDescriptorType:typeUnicodeText];
NSData *data = [unicode data];
NSString *result = [[NSString alloc] initWithCharacters:(unichar*)[data bytes] length:[data length] / sizeof(unichar)];
NSLog(#"Result: %#",result);
}
return 0;
}
How can I implement a loop to switch through all my tabs so it can output all the tab's URLs?
This AppleScript code returns the URLs of all tabs
tell application "Safari" to return URL of tabs of window 1
The result is a list descriptor which must be converted to an NSArray object
int main(int argc, const char * argv[]) {
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:#"tell application \"Safari\" to return URL of tabs of window 1"];
NSDictionary *scriptError = nil;
NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
if(scriptError) {
NSLog(#"Error: %#",scriptError);
} else {
NSAppleEventDescriptor *listDescriptor = [descriptor coerceToDescriptorType:typeAEList];
NSMutableArray *result = [[NSMutableArray alloc] init];
for (NSInteger i = 1; i <= [listDescriptor numberOfItems]; ++i) {
NSAppleEventDescriptor *URLDescriptor = [listDescriptor descriptorAtIndex:i];
[result addObject: URLDescriptor.stringValue];
}
NSLog(#"Result: %#", [result copy]);
}
return 0;
}
Maybe not what you want but here's a solution with Scripting Bridge:
SafariApplication *SafariApp = [SBApplication applicationWithBundleIdentifier:#"com.apple.Safari"];
for (SafariWindow *window in SafariApp.windows)
{
for (SafariTab *tab in window.tabs)
NSLog(#"%#", tab.URL);
}
I have this byte[] data from a webservice that looks like this (this is just a small porton of it):
JVBERi0xLjQgU2hhcnAgU2Nhbm5lZCBJbWFnZVBERgolU2hhcnAgTm9uLUVuY3J5cHRpb24KMyAwIG9iago8PAovVHlwZSAvUGFnZQovUGFyZW50IDEgMCBSCi9SZXNvdXJjZXMgNCAwIFIKL0NvbnRlbnRzIDUgMCBSCi9NZWRpYUJveCBbMCAwIDYxMyA3OTBdCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9Qcm9jU2V0IFsvUERGIC9JbWFnZUJdCi9YT2JqZWN0IDw8IC9JbWcxIDYgMCBSID4+Cj4+CmVuZG9iago1IDAgb2JqCjw8Ci9MZW5ndGggMjcKPj4Kc3RyZWFtCjYxMyAwIDAgNzkwIDAgMCBjbQovSW1nMSBEbwplbmRzdHJlYW0KZW5kb2JqCjYgMCBvYmoKPDwKL1R5cGUgL1hPYmplY3QKL1N1YnR5cGUgL0ltYWdlCi9OYW1lIC9JbWcxCi9GaWx0ZXIgL0NDSVRURmF4RGVjb2RlCi9EZWNvZGVQYXJtcyA8PCAgL0sgLTEgL0NvbHVtbnMgMTcwNCAvUm93cyAyMTk2ID4+Ci9XaWR0aCAxNzA0Ci9IZWlnaHQgMjE5NgovQml0c1BlckNvbXBvbmVudCAxCi9Db2xvclNwYWNlIC9EZXZpY2VHcmF5Ci9MZW5ndGggNyAwIFIKPj4Kc3RyZWFtCvywYWH//////////////////////////X3////////////r5bIVv/Zbqq/D9fH//////////X//ymQ1vH/////X/f///69/9f////+/+vfr//+//9f/79e//9ZZmL/XG//9f/7////X/17////+vde///a/+V+RGlpyuOgQITiPMjojo8gQJTTI
What I am trying to do is put this byte[] data into an NSData variable so I can save this PDF file and display is on my app.
This is what I have tried:
NSArray *byteArray = [dataSource.areaData GetPDFFileData:[NSString stringWithFormat:#"%#",#""]];
unsigned c = byteArray.count;
uint8_t *bytes = malloc(sizeof(*bytes) * c);
unsigned i;
for (i = 0; i < c; i++)
{
NSString *str = [byteArray objectAtIndex:i];
int byte = [str intValue];
bytes[i] = (uint8_t)byte;
}
NSData* data = [NSData dataWithBytes:(const void *)bytes length:sizeof(unsigned char)*c];
but I get this error
-[__NSCFDictionary intValue]: unrecognized selector sent to instance 0x17eb28e0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary intValue]: unrecognized selector sent to instance 0x17eb28e0'
on this line
int byte = [str intValue];
How do I fix this? is there something wrong with my byte[] data or the way I am converting it?
Below is an image of what is in byteArray
Here is my call to get the byte[] from the webservice
-(NSArray *)GetPDFFileData:(NSString *)y
{
NSString *FileBrowserRequestString = [NSString stringWithFormat:#"%#?y=%#",kIP,y];
NSURL *JSONURL = [NSURL URLWithString:FileBrowserRequestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return tableArray;
}
You have an array of dictionary objects where the "data" element contains what looks like a base-64 encoded byte array.
// Untested
NSArray *array = [dataSource.areaData GetPDFFileData:#""];
for (NSDictionary *dict in array) {
NSString *base64 = dict[#"data"];
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64
options:0];
// Do something with data?
}
I have a URL that returns a pretty flat XML file: <entries><title>val1</title><author>Bob</author></entries> The code runs ok:
NSString *urlString = [NSString stringWithFormat:#"http://www.somesite.php?qid=%d", __inum];
NSLog(#"urlString = %#", urlString);
NSURLResponse * response = nil;
NSError * error = nil;
NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:urlString]];
NSData * myData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSLog(#"%#", myData);
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:nil];
TBXMLElement *rootElement = sourceXML.rootXMLElement;
if (rootElement) {
NSLog(#"Root element found...");
TBXMLElement *qaElement1 = [TBXML childElementNamed:#"title" parentElement:rootElement];
if (qaElement1) {
NSString *idAttribute = [TBXML valueOfAttributeNamed:#"title" forElement:qaElement1];
NSLog(#"Got to the 1st call for idAttribute... %#", idAttribute);
}
else { NSLog(#"There is no value for title..."); }
}
else { NSLog(#"Root element must be null..."); }
}
It finds the root element and gets to the call for valueOfAttribute:#"title" but the value is always (null).
So my question: do I have to do something to convert the NSData back to man readable (I was under the impression TBXML gave that option to work with the NSData and did the calculation). If not, what is the call to create (and then use) an NSString in UTF8 from 'myData'?
what is the call to create (and then use) an NSString in UTF8 from 'myData'?
use initWithData:encoding:
NSString *str = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
or stringWithUTF8String: if you know myData is null-terminated UTF8 string
NSString *str = [NSString stringWithUTF8String:[myData bytes]];
Do not ignore error.
NSError *error = nil;
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:&error];
if (error) {
// handle it, at least log it
}
I m using below mentioned line in a function
NSMutableData *data = [[NSMutableData alloc] init];
And I m calling this function a no of time (e.g. 100 times). So my problem is that initially for about 60 times or more it is working properly but after that it gives me "BAD_EXC_ACCESS"
Function is given below
+ (NSString *) recvToFile:(NSString *)_fileName {
#try {
int _sz = [self recvNumber:4];
uint8_t t[_sz];
NSMutableData *data = [[NSMutableData alloc] init];
NSMutableData *fileData = [[NSMutableData alloc] init];
long _pos = 0;
NSString *_fullPath = _fileName;
while (_sz > _pos) {
long _c = [m_sin read:t maxLength:_sz];
_pos += _c;
data = [NSData dataWithBytes:t length:_c];
if([Misc checkFileExists:_fileName]==nil)
[[NSFileManager defaultManager] createFileAtPath:_fullPath contents:nil attributes:nil];
[fileData appendData:data];
}
[fileData writeToFile:_fullPath atomically:YES];
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:_fullPath error:nil];
long long length = [[attr valueForKey:#"NSFileSize"] intValue];
if (length >= _sz)
return (_fullPath);
}
#catch (NSException * e) {
}
return (nil);
}
And I m calling this function every time i receive a file. I want to save file from bytes
You should not initialize data here:
NSMutableData *data = [[NSMutableData alloc] init];
just initialize the variable to nil;
NSMutableData* data = nil;
Try adding data like this to nsmutabledata
[data appendBytes:t length:_c];