I have a large dictionary (partial example below - there are 26 products in total) that I need to send back to a ColdFusion web service. I was able to make a connection to the web service and when checking the NSHTTPURLResponse statusCode I get 200, which indicates the service is receiving and returning something (right?) but when I check the return I get HTML results, part of which states an error:
coldfusion.runtime.MissingArgumentException: The PAJSONSTRING parameter to the setPurchaseAgreements function is required but was not passed in.
which to me seems that I am not setting the value for the variable PAJSONSTRING. So my question is how would I be able to pass this JSON to that variable? I thought of the query string but when that would end up passing somewhere between 5000 and 7000 characters depending on what the user is sending back. But I can't seem to find an example of how to set a parameter value using POST. Any thoughts would be appreciated.
PA = {
"CUSTOMER_ID" = xxxxxxx;
"GROSS_GROWTH_NO_YF_FLU" = 39385;
"GROSS_GROWTH_ONLINE_DISC" = 394;
"GROSS_GROWTH_SALES" = 56500;
"GROSS_PROJECTED_NO_YF_FLU" = 35805;
"GROSS_PROJECTED_ONLINE_DISC" = 358;
"GROSS_PROJECTED_SALES" = 52920;
"GROSS_SALES" = 0;
"GROSS_SALES_CUST_PRICE_LIST" = 0;
"GROWTH_MATCH_REBATE_AMT" = 3509;
"GROWTH_NET_SALES" = 56500;
"GROWTH_NET_SALES_NO_YF_FLU" = 394;
"GROWTH_PROJ_SALES_NO_YF_FLU" = 3509;
"GROWTH_REBATE_AMT" = 3509;
"GROWTH_REBATE_PCT" = 9;
"MATCH_GRTH_REBATE_GRTH_SALES" = "";
"MATCH_NET_SALES" = 49200;
"MATCH_PROJ_SALES_NO_YF_FLU" = 35447;
"MATCH_REBATE_AMT" = 3190;
"MATCH_REBATE_NET_DISCOUNT_SLS" = "";
"MTH_GRTH_RBT_GRTH_NET_DISC_SLS" = "";
"NEW_PRICE_DISC_NET_DISC" = "";
"ONLINE_DISCOUNT_PCT" = 1;
"OPER_ID" = xxxxxx;
"PA_CREATE_DT" = "2014-01-03 05:00:00 +0000";
"PA_ID" = 0;
"PA_NAME" = "Copy of 8";
"PA_STATUS_ID" = 2;
"PRICELIST_TYPE_ID" = 5;
"PRICE_LIST_GROWTH_SALES" = "";
"PRICE_LIST_PROJECTED_SALES" = "";
"REBATE_ELG_PROD_COUNT" = 0;
"SALES_ROSTER_ID" = 20016;
"START_DT" = "2014-01-03 17:56:12 +0000";
"STATUS_PRICE_LIST_NET_DISC_SLS" = "";
"STATUS_PRICE_LIST_PROJ_SALES" = "";
"TOTAL_GRTH_MATCH_REBATE_AMT" = "";
"UPFRONT_DISCOUNT_PCT" = 0;
};
PRODUCTS = (
{
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
},
{
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
"DISCOUNT_DOSE_PRICE" = 8;
"DISCOUNT_UNIT_PRICE" = 80;
"GROWTH_DOSES" = 0;
"GROWTH_PROJECTED" = 0;
"LIST_DOSE_PRICE" = 0;
"OPER_ID" = 20016;
"PA_PRODUCT_ID" = xxxxx;
"PRODUCT_ID" = xxxxx;
"SALES_PROJECTED" = 0;
"SUGGESTED_DOSES" = 0;
"USER_SELECTED_DOSES" = 0;
}
);
}
partial code...
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictJSONData options:NSJSONWritingPrettyPrinted error:&error];
NSString* urlString = SERVICE_SET_PA;
NSURL* url = [NSURL URLWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse* response, NSData* data, NSError* responseError) {
id results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:nil];
NSString* strResults = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
DDLogVerbose(#"%#", strResults);
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*) response;
if (data.length > 0 && responseError == nil) {
DDLogVerbose(#"%#", httpResponse.allHeaderFields);
[self receivedData:data];
} else if (data.length == 0 && error == nil) {
[self emptyReply];
} else if (responseError != nil) {
[self displayError: error];
}
}];
Edit: Logging jsonData shows this (partial post):
<7b0a2020 22504122 203a207b 0a202020 20225041 5f494422 203a2030 2c0a2020 2020224d 41544348 5f475254 485f5245 42415445 5f475254 485f5341 4c455322 203a2022 222c0a20 20202022 50415f53 54415455 535f4944 22203a20 322c0a20 20202022 47524f57 54485f50 524f4a5f 53414c45 535f4e4f 5f59465f 464c5522 203a2033 3530392c...
Deserializing it and logging it show this (partial post):
PA = {
"CUSTOMER_ID" = 955728;
"GROSS_GROWTH_NO_YF_FLU" = 39385;
"GROSS_GROWTH_ONLINE_DISC" = 394;
"GROSS_GROWTH_SALES" = 56500;
"GROSS_PROJECTED_NO_YF_FLU" = 35805;
"GROSS_PROJECTED_ONLINE_DISC" = 358;
"GROSS_PROJECTED_SALES" = 52920;
"GROSS_SALES" = 0;
"GROSS_SALES_CUST_PRICE_LIST" = 0;
"GROWTH_MATCH_REBATE_AMT" = 3509;
"GROWTH_NET_SALES" = 56500;
"GROWTH_NET_SALES_NO_YF_FLU" = 394;
"GROWTH_PROJ_SALES_NO_YF_FLU" = 3509;
...
so at least to this extent it looks fine.
I recommend using the AFNetworking Framework (osx&ios).
(https://github.com/AFNetworking/AFNetworking)
Example (from documentation)
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Related
First of all, sorry for my bad English.
I just started with the Objective-C a couple of week ago. I'm doing a project that require me to compared two audio signals recorded from two iOS devices. So far, I managed to record two .aif files from an iPhone 4s and iPhone 4. Then I try to apply the following algorithm A Highly Robust Audio Fingerprinting System. by: Jaap Haitsma" to get two fingerprints (in binary bit patterns 101011010) and then compare them with each other bits by bits. But so far, the result I got is somewhere between 45% and 55% which is pretty much the random probability between 0s and 1s. So can somebody give me any advice. Here's the code so far:
CalculateFingerprint *myCalculateFingerprint = [CalculateFingerprint alloc];
SInt16 *inputBuffer;
path4 = [documentsDirectory stringByAppendingPathComponent:fileName4];
/////////Calculate for the 4 file
fileURL = [NSURL fileURLWithPath:path4];
status = AudioFileOpenURL((__bridge CFURLRef)fileURL, kAudioFileReadPermission,kAudioFileAIFFType, &myAudioFile);
status = AudioFileGetPropertyInfo(myAudioFile,
kAudioFilePropertyAudioDataPacketCount,
&propertySizeDataPacketCount,
&writabilityDataPacketCount);
status = AudioFileGetProperty(myAudioFile,
kAudioFilePropertyAudioDataPacketCount,
&propertySizeDataPacketCount,
&numberOfPackets);
status = AudioFileGetPropertyInfo (myAudioFile,
kAudioFilePropertyMaximumPacketSize,
&propertySizeMaxPacketSize,
&writabilityMaxPacketSize);
status = AudioFileGetProperty(myAudioFile,
kAudioFilePropertyMaximumPacketSize,
&propertySizeMaxPacketSize,
&maxPacketSize);
inputBuffer = (SInt16 *)malloc(numberOfPackets * maxPacketSize);
currentPacket = 0;
status = AudioFileReadPackets(myAudioFile,
false, &numberOfBytesRead,
NULL,
currentPacket,
&numberOfPackets,
inputBuffer);
[myCalculateFingerprint calculateFingerprint:inputBuffer sampleCount:numberOfPackets index:indexFile];
status = AudioFileClose(myAudioFile);
Here's the calculation of fingerprint code:
-(void)calculateFingerprint :(SInt16*)samples
sampleCount:(int)sampleCount
index:(int)indexFile{
//Divide the audio signal into 32 frames
frames myFrames [32];
int stepFrames = sampleCount / 62;
int number = 0;
int index ;
for (int i = 0; i < 32; ++i){
index = 0;
myFrames[i].start = number;
myFrames[i].end = number + (32*stepFrames);
myFrames[i].dataFrames = (SInt16*)malloc((myFrames[i].end -number+1)*sizeof(SInt16));
for (int j = number;j<=myFrames[i].end; ++j){
myFrames[i].dataFrames[index] = samples[j];
++index;
}
number = number + stepFrames;
}
//Calculate FFT for each of the audio signal frames.
CalculateFFT *myCalculateFFT = [[CalculateFFT alloc] init];
theFFT myFFTData [32];
for (int i = 0; i <32; ++i){
myFFTData[i].FFTdata = [myCalculateFFT calculateFFTForData:myFrames[i].dataFrames];
}
//each index represent the frequency as followed:
// index i is frequency i * 44100/1024
//We only need 33 bands from 300 Hz to 2000Hz, so we will get the FFTdata from the index 7 to 40
float energy [33][33];
for (int i =0; i < 33; ++i){
energy[0][i] = 0;
}
int stepBand;
for (int i = 1; i < 33; ++i){
for (int j = 0; j < 33; ++j){
energy[i][j] = myFFTData[i].FFTdata[j+7];
}
}
//next we calculate the bits for the audio fingerprint
Float32 check = 0;
int fingerPrint [32][32];
NSMutableString *result = [[NSMutableString alloc]init];
for (int i = 0; i < 32; ++i){
for (int j = 0; j <32; ++j){
check = energy[i+1][j] -energy[i+1][j+1] -energy[i][j] +energy[i][j+1];
if (check > 0){
fingerPrint[i][j] = 1;//[tempBitFingerPrint addObject:[NSNumber numberWithInt:1]];
}else {
fingerPrint[i][j] = 0;//[tempBitFingerPrint addObject:[NSNumber numberWithInt:0]];
}
[result appendString:[NSString stringWithFormat:#"%d",fingerPrint[i][j]]];
}
}
And finally the FFT calculation code:
-(void)FFTSetup{
UInt32 maxFrames = 1024;
originalReal = (float*) malloc(maxFrames*sizeof(float));
originalRealTransfer = (float*)malloc(maxFrames*sizeof(float));
obtainedReal = (float*) malloc(maxFrames *sizeof(float));
freqArray = (Float32*) malloc((maxFrames/2) *sizeof(Float32));
fftLog2n = log2f(maxFrames);
fftN = 1 << fftLog2n;
fftNOver2 = maxFrames/2;
fftBufferCapacity = maxFrames;
fftIndex = 0;
fftA.realp = (float*)malloc(fftNOver2*sizeof(float));
fftA.imagp = (float*)malloc(fftNOver2*sizeof(float));
fftSetup = vDSP_create_fftsetup(fftLog2n,FFT_RADIX2);
}
-(Float32*) calculateFFTForData:(SInt16*)sampleData
{
[self FFTSetup];
int stride = 1;
for (int i = 0; i < fftN; ++i){
originalReal[i] = (float) sampleData[i];
}
UInt32 maxFrames = 1024;
//Apply Hann window on the data
int windowSize = maxFrames;
float * window = (float*)malloc(sizeof(float)*windowSize);
memset(window, 0, sizeof(float)*windowSize);
vDSP_hann_window(window, windowSize, vDSP_HANN_NORM);
vDSP_vmul(originalReal,1,window,1,originalRealTransfer,1,windowSize);
vDSP_ctoz((COMPLEX*) originalRealTransfer,2,&fftA,1,fftNOver2);
vDSP_fft_zrip(fftSetup,&fftA, stride,fftLog2n,FFT_FORWARD);
float scale = (float) 1.0 /(2*fftN);
vDSP_vsmul(fftA.realp,1,&scale,fftA.realp,1,fftNOver2);
vDSP_vsmul(fftA.imagp,1,&scale,fftA.imagp,1,fftNOver2);
vDSP_ztoc(&fftA,1,(COMPLEX*)obtainedReal,2,fftNOver2);
int index = 0;
NSMutableString *testResult = [[NSMutableString alloc]init];
for (int i = 0; i < fftN; i=i+2){
freqArray[index] = (obtainedReal[i]*obtainedReal[i])+(obtainedReal[i+1]*obtainedReal[i+1]);
[testResult appendString:[NSString stringWithFormat:#"%f ",freqArray[index]]];
++index;
}
return freqArray;
}
I've been working on this task for 12 days and i cant find any solution pleaaaaase help
i'm supposed to load about 80 m4a files and play some of them with augraph which contains mixer and remoteIO units thats how i load the files
OSStatus result;
for (int i = 0; i < [filePaths count]; i++) {
NSMutableArray *linearr=[[NSMutableArray alloc] init];
for (int j = 0; j < [[filePaths objectAtIndex:i] count]; j++) {
NSString *str=[[filePaths objectAtIndex:i] objectAtIndex:j];
CFURLRef audioFileURL = CFURLCreateFromFileSystemRepresentation (NULL, (const UInt8 *)[str cStringUsingEncoding:[NSString defaultCStringEncoding]] , strlen([str cStringUsingEncoding:[NSString defaultCStringEncoding]]), false);
ExtAudioFileRef audiofile;
ExtAudioFileOpenURL(audioFileURL, &audiofile);
assert(audiofile);
OSStatus err;
AudioStreamBasicDescription fileFormat;
UInt32 size = sizeof(fileFormat);
err = ExtAudioFileGetProperty(audiofile, kExtAudioFileProperty_FileDataFormat, &size, &fileFormat);
AudioFileID aFile;
//size = sizeof(aFile);
PropertySize =sizeof(PacketsToRead);
err = ExtAudioFileGetProperty(audiofile, kExtAudioFileProperty_AudioFile, &PropertySize, &aFile);
AudioFileTypeID fileType;
PropertySize = sizeof(fileType);
err = AudioFileGetProperty(aFile, kAudioFilePropertyFileFormat, &PropertySize, &fileType);
AudioStreamBasicDescription clientFormat;
bzero(&clientFormat, sizeof(clientFormat));
clientFormat.mChannelsPerFrame = 2;
clientFormat.mBytesPerFrame = 4;
clientFormat.mBytesPerPacket = clientFormat.mBytesPerFrame;
clientFormat.mFramesPerPacket = 1;
clientFormat.mBitsPerChannel = 32;
clientFormat.mFormatID = kAudioFormatLinearPCM;
clientFormat.mSampleRate = 44100.00;
clientFormat.mFormatFlags =kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsNonInterleaved; //kLinearPCMFormatFlagIsFloat | kAudioFormatFlagIsNonInterleaved;
err = ExtAudioFileSetProperty(audiofile, kExtAudioFileProperty_ClientDataFormat, sizeof(clientFormat), &clientFormat);
SInt64 numFrames = 0;
PropertySize = sizeof(numFrames);
err = ExtAudioFileGetProperty(audiofile, kExtAudioFileProperty_FileLengthFrames, &PropertySize, &numFrames);
NSNumber *pc = [NSNumber numberWithLongLong:numFrames];
[[packetCount objectAtIndex:i] replaceObjectAtIndex:j withObject:pc];
// create the buffers for reading in data
bufferList = malloc(sizeof(AudioBufferList) + sizeof(AudioBuffer) * (clientFormat.mChannelsPerFrame - 1));
bufferList->mNumberBuffers = clientFormat.mChannelsPerFrame;
for (int ii=0; ii < bufferList->mNumberBuffers; ++ii) {
bufferList->mBuffers[ii].mDataByteSize = sizeof(float) * numFrames;
bufferList->mBuffers[ii].mNumberChannels = 2;
bufferList->mBuffers[ii].mData = malloc(bufferList->mBuffers[ii].mDataByteSize);
}
UInt32 rFrames = 0;
rFrames =(UInt32)numFrames;
err = ExtAudioFileRead(audiofile, &rFrames, bufferList);
[linearr addObject:[NSData dataWithBytes:bufferList->mBuffers[1].mData length:numFrames]];
err = ExtAudioFileDispose(audiofile);
}
[audioData addObject:linearr];
}
and that's how i play it:
UInt32 *buslist;
buslist=( UInt32*)[[[audioData objectAtIndex:0] objectAtIndex:4]bytes ];
in rendercallback func:
for (int i = 0 ; i < ioData->mNumberBuffers; i++){
UInt32 *au3=au->mBuffers[0].mData;
AudioBuffer buffer = ioData->mBuffers[i];
UInt32 *frameBuffer = buffer.mData;
for (int j = 0; j < inNumberFrames; j++)
{
frameBuffer[j] = buflist[counter];
if(counter>=529200)
counter=0;
else
counter++;
}}}
Now when i play the sound i get the first part played with double speed then the second part only distortion.
I was having the exact same problem I think;
The incoming sound was at a lower sample rate, so the array I allocated wasn't big enough for the higher sample rate of the auGraph, and was too fast and short.
make sure you allocate an array to read the file something like this:
sarray->frames = totalFramesInFile * graphSampleRate / fileAudioFormat.mSampleRate;
I have a problem when trying to retrieve values from an array.
I want to get all the values from this array in order to display them in a IUTableView.
Should I use a double for function ?
{
1 = {
dishId = 1;
dishName = "Tomato Salades";
dishPrice = 13;
dishTypeId = 1;
dishTypeName = Starter;
};
2 = {
dishId = 2;
dishName = "Leeks Salades";
dishPrice = 12;
dishTypeId = 1;
dishTypeName = Starter;
};
3 = {
dishId = 3;
dishName = Fries;
dishPrice = 14;
dishTypeId = 2;
dishTypeName = "Main Course";
};
4 = {
dishId = 4;
dishName = Beef;
dishPrice = 15;
dishTypeId = 2;
dishTypeName = "Main Course";
};
7 = {
dishId = 7;
dishName = "Cheese Cake";
dishPrice = 8;
dishTypeId = 3;
dishTypeName = Dessert;
};
menuCountry = France;
menuDescription = "un menu pas comme les autres pour une region pas comme les autres";
menuId = 1;
menuName = "Autour de l\\Alsace";
menuState = 1;
}
This is my Python code which creates a Dictionary in a Array :
def getDishOfTheWeek():
menuArray = []
menuDic = Ddict(dict)
for menu in Menus.select().where(state=True):
menuDic['menuId']=menu.id
menuDic['menuName']=menu.name
menuDic['menuCountry']=menu.country.name
menuDic['menuDescription']=menu.description
menuDic['menuState']=menu.state
for d in DishMenuRels.select().where(menu = menu.id).join(Dishes).join(DishTypes).order_by((DishTypes,'name')):
menuDic[str(d.dish.id)] = {}
menuDic[str(d.dish.id)]['dishTypeName'] = d.dish.dishType.name
menuDic[str(d.dish.id)]['dishTypeId'] = d.dish.dishType.id
menuDic[str(d.dish.id)]['dishId'] = d.dish.id
menuDic[str(d.dish.id)]['dishName'] = d.dish.name
menuDic[str(d.dish.id)]['dishPrice'] = d.dish.price
menuArray.append(menuDic)
return json.dumps(menuArray)
This is my Objectiv-C code in order to get the DataJson and put it in an Array:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
[[ConnectionSingleton getInstance] setConnectionMade:YES];
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
output = [output substringToIndex:[output length] - 2];
if (nil != output) {
NSError* error; // Obligatoir pour le JSON
menu = [NSJSONSerialization JSONObjectWithData:[output dataUsingEncoding:NSUTF8StringEncoding] options:
NSJSONReadingMutableContainers error:&error]; // Put Json in the Array
[[self tableView] reloadData]; // Reload Array to populate it
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
break;
default:
NSLog(#"Unknown event");
}
}
I think this should do the trick
NSArray *firstArray = [NSArray arrayWithObjects:[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil], [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],[NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",nil],#"String",#"String",#"String",#"String",#"String",nil];
NSInteger count_i = firstArray.count;
NSInteger count_j;
id val;
for (NSInteger i = 0; i < count_i; i++) {
if ([[firstArray objectAtIndex:i] isKindOfClass:[NSArray class]]) {
count_j = [[firstArray objectAtIndex:i] count];
for (NSUInteger j = 0; j < count_j; j++) {
val = [[firstArray objectAtIndex:i] objectAtIndex:j];
NSLog(#"%#",val);
}
}else{
val = [firstArray objectAtIndex:i];
NSLog(#"%#",val);
}
}
But your values are of different types, so you have to deal with them in different ways depending of the value of j.
NSLog give me this when i print some NSDictionary object. I see, that in this NSDictionary are few NSDictionary objects. i must to send this to UITextView, but this must be one list without {ExifAux}, {Exif}, {IPTC}, {TIFF}. how can i do this?
2012-01-21 13:33:23.818 foto-edytor[7838:17903] {
ColorModel = RGB;
DPIHeight = 240;
DPIWidth = 240;
Depth = 8;
PixelHeight = 900;
PixelWidth = 598;
"{ExifAux}" = {
ImageNumber = 5280;
LensID = 159;
LensInfo = (
35,
35,
"1.8",
"1.8"
);
LensModel = "35.0 mm f/1.8";
SerialNumber = 6055523;
};
"{Exif}" = {
ApertureValue = "3.356144";
BodySerialNumber = 6055523;
ColorSpace = 1;
ComponentsConfiguration = (
1,
2,
3,
0
);
Contrast = 0;
CustomRendered = 0;
DateTimeDigitized = "2011:11:12 11:54:18";
DateTimeOriginal = "2011:11:12 11:54:18";
DigitalZoomRatio = 1;
ExifVersion = (
2,
2,
1
);
ExposureBiasValue = "-1.333333";
ExposureMode = 0;
ExposureProgram = 3;
ExposureTime = "0.01666667";
FNumber = "3.2";
FileSource = 3;
Flash = 0;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 52;
FocalLength = 35;
GainControl = 1;
ISOSpeedRatings = (
400
);
LensModel = "35.0 mm f/1.8";
LensSpecification = (
35,
35,
"1.8",
"1.8"
);
LightSource = 0;
MaxApertureValue = "1.6";
MeteringMode = 2;
PixelXDimension = 1442971648;
PixelYDimension = "-2080178176";
Saturation = 0;
SceneCaptureType = 0;
SceneType = 1;
SensingMethod = 2;
Sharpness = 0;
ShutterSpeedValue = "5.906891";
SubjectDistRange = 0;
SubjectDistance = "1.41";
SubsecTimeDigitized = 25;
SubsecTimeOriginal = 25;
UserComment = SZULC;
WhiteBalance = 0;
};
"{IPTC}" = {
Byline = "SZULC TOMASZ";
CopyrightNotice = "SZULC TOMASZ";
};
"{TIFF}" = {
Artist = "SZULC TOMASZ";
Copyright = "SZULC TOMASZ";
DateTime = "2012:01:20 17:50:58";
Make = "NIKON CORPORATION";
Model = "NIKON D300S";
ResolutionUnit = 2;
Software = "Ver.1.01";
XResolution = 240;
YResolution = 240;
"_YCbCrPositioning" = 1;
};
}
It's not the most beautiful way, but I guess this should work:
- (NSString *)stringOutputForDictionary:(NSDictionary *)inputDict {
NSMutableString * outputString = [NSMutableString stringWithCapacity:256];
NSArray * allKeys = [inputDict allKeys];
for (NSString * key in allKeys) {
if ([[inputDict objectForKey:key] isKindOfClass:[NSDictionary class]]) {
[outputString appendString: [self stringOutputForDictionary: (NSDictionary *)inputDict]];
}
else {
[outputString appendString: key];
[outputString appendString: #": "];
[outputString appendString: [[inputDict objectForKey: key] description]];
}
[outputString appendString: #"\n"];
}
return [NSString stringWithString: outputString];
}
I am working on a App that makes use of a JSON API and I am Using the JSON for Objective C Framework to get the Data into a NSDictionary. The dictionary loos like this:
({
admitted = "<null>";
agreed = "<null>";
"area_id" = 1;
"area_name" = "Digitales, Urheber-/Patentrecht, Datenschutz";
created = "2010-08-17 12:41:03";
"current_draft_content" = Bla Bla Bla";
"current_draft_created" = "2010-08-17 12:42:44";
"current_draft_formatting_engine" = compat;
"discussion_url" = "http://piratenpad.de/OpenSourceZwang";
id = 502;
"informed_supporter_count" = 11;
"issue_accepted" = "";
"issue_admission_time" = "8 days";
"issue_closed" = "";
"issue_created" = "2010-08-17 12:41:03";
"issue_discussion_time" = "15 days";
"issue_fully_frozen" = "";
"issue_half_frozen" = "";
"issue_id" = 242;
"issue_population" = 372;
"issue_ranks_available" = 0;
"issue_state" = new;
"issue_verification_time" = "8 days";
"issue_vote_later" = 0;
"issue_vote_now" = 0;
"issue_voter_count" = "<null>";
"issue_voting_time" = "8 days";
name = "Alte & unsupportete Software, muss Open Source werden";
"negative_votes" = "<null>";
"policy_initiative_quorum_den" = 100;
"policy_initiative_quorum_num" = 10;
"policy_issue_quorum_den" = 100;
"policy_issue_quorum_num" = 10;
"policy_majority_den" = 2;
"policy_majority_num" = 1;
"policy_majority_strict" = 1;
"positive_votes" = "<null>";
rank = "<null>";
revoked = "<null>";
"satisfied_informed_supporter_count" = 7;
"satisfied_supporter_count" = 7;
"suggested_initiative_id" = "<null>";
"supporter_count" = 11;
},
{
admitted = "<null>";
agreed = "<null>";
"area_id" = 1;
"area_name" = "Digitales, Urheber-/Patentrecht, Datenschutz";
created = "2010-08-17 14:09:14";
"current_draft_content" = "Bla Bla Bla";
"current_draft_created" = "2010-08-17 14:09:31";
"current_draft_formatting_engine" = compat;
"discussion_url" = "";
id = 508;
"informed_supporter_count" = 0;
"issue_accepted" = "2010-08-14 01:51:45";
"issue_admission_time" = "15 days";
"issue_closed" = "";
"issue_created" = "2010-08-14 01:34:26";
"issue_discussion_time" = "30 days";
"issue_fully_frozen" = "";
"issue_half_frozen" = "";
"issue_id" = 30;
"issue_population" = 603;
"issue_ranks_available" = 0;
"issue_state" = accepted;
"issue_verification_time" = "15 days";
"issue_vote_later" = 9;
"issue_vote_now" = 0;
"issue_voter_count" = "<null>";
"issue_voting_time" = "15 days";
name = "Grundrecht: Alternative Formulierung";
"negative_votes" = "<null>";
"policy_initiative_quorum_den" = 100;
"policy_initiative_quorum_num" = 10;
"policy_issue_quorum_den" = 100;
"policy_issue_quorum_num" = 10;
"policy_majority_den" = 3;
"policy_majority_num" = 2;
"policy_majority_strict" = 0;
"positive_votes" = "<null>";
rank = "<null>";
revoked = {
};
"satisfied_informed_supporter_count" = 0;
"satisfied_supporter_count" = 0;
"suggested_initiative_id" = "<null>";
"supporter_count" = 0;
}
)
What is a good way to get all object where the "issue_id" is 2 oder 6 or what ever to display a grouped UITabeView with all objects with the same "issue_id" in one group?
You can use NSSortDescriptor to sort:
NSSortDescriptor *dateSortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"issue_id" ascending:YES selector:#selector(compare:)] autorelease];
[youDictionaryArray sortUsingDescriptors:[NSArray arrayWithObjects:dateSortDescriptor, nil]];
And/or NSPredicate to get some ID only:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(issue_id == %i)", 2];
NSArray *newArray = [youDictionaryArray filteredArrayUsingPredicate:predicate];
There are several ways. You can use NSPredicate and use the NSArray method -filteredArrayUsingPredicate:. Or on iOS 4 you use a filtering block: -indexesOfObjectsPassingTest: then use -objectsAtIndexes: to get the objects.
Otherwise the best is you just iterate through the array and filter the items you want into a new one:
// Given a NSArray *items
NSMutableArray *filteredItems = [NSMutableArray array];
for (NSDictionary *item in items) {
if (/* your condition */) {
[filteredItems addObject: item];
}
}