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?
}
Related
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
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 have the following data saved as an NSString :
{
Key = ID;
Value = {
Content = 268;
Type = Text;
};
},
{
Key = ContractTemplateId;
Value = {
Content = 65;
Type = Text;
};
},
I want to convert this data to an NSDictionary containing the key value pairs.
I am trying first to convert the NSString to a JSON objects as follows :
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
However when I try :
NSString * test = [json objectForKey:#"ID"];
NSLog(#"TEST IS %#", test);
I receive the value as NULL.
Can anyone suggest what is the problem ?
I believe you are misinterpreting the JSON format for key values. You should store your string as
NSString *jsonString = #"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now if you do following NSLog statement
NSLog(#"%#",[json objectForKey:#"ID"]);
Result would be another NSDictionary.
{
Content = 268;
type = text;
}
I think you get the array from response so you have to assign response to array.
NSError *err = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
NSDictionary *dictionary = [array objectAtIndex:0];NSString *test = [dictionary objectForKey:#"ID"];NSLog(#"Test is %#",test);
Use this code where str is your JSON string:
NSError *err = nil;
NSArray *arr =
[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&err];
// access the dictionaries
NSMutableDictionary *dict = arr[0];
for (NSMutableDictionary *dictionary in arr) {
// do something using dictionary
}
Swift 3:
if let jsonString = styleDictionary as? String {
let objectData = jsonString.data(using: String.Encoding.utf8)
do {
let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers)
print(String(describing: json))
} catch {
// Handle error
print(error)
}
}
Use the following code to get the response object from the AFHTTPSessionManager failure block; then you can convert the generic type into the required data type:
id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
I am trying to parse some Json with Objective C.
My problem is that I am getting the correct json back but when I try parse some of the json my app crashes.
// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",strResult);
NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"AssetDesc"]; //2
NSLog(#"value: %#", defineJsonData); //3
Here is my json:
[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
I am trying to get the AssestName out of the string. I must be doing something wrong.
The whole thing is an array containing a dictionary, not a dictionary containing an array...
This is a very dirty way to get the value you want - you want to write something more safe than this. Try checking the type of class returned before you try to use it...
NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSDictionary* defineJsonData = [json lastObject]; //2
NSLog(#"value: %#", [defineJsonData objectForKey:#"AssetDesc"]); //3
i'm pulling a 2 dimensional array from a remote server:
- (NSMutableArray*)qBlock{
NSURL *url = [NSURL URLWithString:#"http://wsome.php"];
NSError *error;
NSStringEncoding encoding;
NSString *response = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSMutableArray *sample = [responseString JSONValue];
return sample;
}
and putting them into:
NSMutableArray *qnBlock1 = [self qBlock];
NSString *answer1 = [NSString stringWithFormat:[[qnBlock1 objectAtIndex:0]objectAtIndex:1]];
answer = [[NSMutableDictionary alloc]init];
[answer setObject:answer1 forKey:#"1"];
question1.text = [[qnBlock1 objectAtIndex:0] objectAtIndex:0];
label1a.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:2];
label1b.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:3];
label1c.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:4];
label1d.text = [[qnBlock1 objectAtIndex:0]objectAtIndex:5];
I received this error during runtime
-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6c179502012-04-30 09:43:50.794 AppName[371:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6c17950'
Is this due to syntax issue for 2 dimensional array?
You're not getting back a multi-dimensional array. You're getting back an array of NSDictionary objects. The error you got indicates that you're trying to send the message objectAtIndex: to an NSDictionary object, which fails since it has no such selector.
Update:
After chatting on the side, it became apparent that the following was true:
The user was using the SBJson library to parse the return value from his php web service.
The return value was either:
An NSDictionary with each key being the text representation of its (non-index-based) location in the list (#"1", #"2", etc...) and each value being an NSArray of NSString objects, or
An NSArray of NSString objects (seems to be the way a single "answer" returns)
Here's the code I supplied to let him iterate through his return value:
NSURL *url = [NSURL URLWithString:#"{his url}"];
NSError *error;
NSStringEncoding encoding;
NSString *response = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&encoding error:&error];
const char *convert = [response UTF8String];
NSString *responseString = [NSString stringWithUTF8String:convert];
NSLog(#"%#", responseString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
id sample = [parser objectWithString:responseString];
if ([sample isKindOfClass:[NSDictionary class]]) {
for (id item in sample) {
NSLog(#"%#", [item description]);
NSArray *subArray = [sample objectForKey:item]; // b/c I know it's an array
for (NSString *str in subArray) {
NSLog(#"item: %#", str);
}
}
} else if ([sample isKindOfClass:[NSArray class]]) {
for (NSString *str in sample) {
NSLog(#"item: %#", str);
}
}
Hope it helps, J!
I think from your error message, you're sending objectAtIndex to a dictionary. NSDictionary doesn't have such a method. You should use objectForKey instead.