Convert NSData (retrieved from wcf ) to NSArray - ios

I want to convert NSData, which I get it by accessing web service, to NSArray. How can I do it?
Here is the structure that I want to convert from NSData:
NSArray:
NSDictionary1 : roomName departmentName
NSDictionary2 : roomName departmentName
NSDictionary3 : roomName departmentName
NSDictionary4 : roomName departmentName
NSDictionary5 : roomName departmentName
...
GetRoomList method of the web service returns a list. The structure of the list is above. Code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *soapMessage = [NSString stringWithFormat:#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><m:GetRoomList xmlns:m=\"http://http://portNumber/ilacDirektif.svc/\"><departId xsi:type=\"xsd:int\">0</departId><roomId xsi:type=\"xsd:int\">0</roomId></m:GetRoomList></SOAP-ENV:Body></SOAP-ENV:Envelope>"];
NSURL *url=[NSURL URLWithString:#"http://port number/ilacDirektif.svc/"];
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/ilacDirektif.svc" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"port number" forHTTPHeaderField:#"Host"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse* response = nil;
NSData *data =[NSURLConnection sendSynchronousRequest: theRequest returningResponse: &response error: nil];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:data];
if(array){NSLog(#"%#",array); }else{ NSLog(#"Failed"); }
if (data) {NSLog(#"%#",data);} else { NSLog(#"Failed");}
}
Error:
2013-05-31 09:59:45.208 IlacOrder[18513:11303] -[__NSCFData getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860 2013-05-31 09:59:45.222 IlacOrder[18513:11303] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFData
getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860'
* First throw call stack: (0x1c8e012 0x10cbe7e 0x1d194bd 0x1c7dbbc 0x1c7d94e 0xacc7b4 0xacc762 0xafac85 0xb22c7a 0x2a55 0xf4817 0xf4882
0xf4b2a 0x10bef5 0x10bfdb 0x10c286 0x10c381 0x10ceab 0x10d4a3 0x10d098
0x2460 0x10df705 0x16920 0x168b8 0xd7671 0xd7bcf 0xd6d38 0x4633f
0x46552 0x243aa 0x15cf8 0x1be9df9 0x1be9ad0 0x1c03bf5 0x1c03962
0x1c34bb6 0x1c33f44 0x1c33e1b 0x1be87e3 0x1be8668 0x1365c 0x1ded
0x1d15 0x1) libc++abi.dylib: terminate called throwing an exception
The function in .svc:
public List<DepartmentRoom>GetRoomList(int roomId,int departId()){
return manager.GetRoomList(roomId,departId);
}
GetRoomList:
public List<DepartmentRoom> GetRoomList(int departId,int roomId){
var cmd = OracleHelper.GetOracleCommand(_conn, StoredProcedure.Procedure1);
if (_conn.State == ConnectionState.Closed)
_conn.Open();
OracleCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["P_DEPARTID"].Value = departId;
cmd.Parameters["P_ROOMID"].Value = roomId;
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
object o = cmd.Parameters["P_REF"].Value;
var roomList = new List<DepartmentRoom>();
while (dr.Read())
{
var departmentRoom = new DepartmentRoom
{
DepartId = Convert.ToInt32(dr["DEPARTID"]),
DepartmentName = dr["DEPART"].ToString(),
RoomId = Convert.ToInt32(dr["ROOMID"]),
RoomName = dr["ROOM"].ToString()
};
roomList.Add(departmentRoom);
}
return roomList;
}

Perhaps it would be worth reading the documentation of the methods and classes you are trying to use. unarchiveObjectWithFile: takes a file path as its argument, not an NSData. Finding the method in the docs that takes an NSData as its input is left to you as an exercise.

This worked for me:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:REQIP]];
NSData *myPostData = [[NSString stringWithFormat:#"{\"departId\":%d,\"roomId\":%d}",departId,roomId] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[request setPostBody:myMutablePostData];
[request setRequestMethod:#"GET"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startSynchronous];
NSMutableArray *list =[[NSMutableArray alloc]init];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:[[request responseString]dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingMutableContainers error:nil ];
for(NSDictionary *theItem in [jsonObjects objectForKey:#"RequestMethodResult"]){
[list addObject:[[ClassModel alloc]initWithDictionary:theItem]];
}
return list;
ClassModel is the structure of the Dictionary that each object item of NSMutableArray is.

Related

IOS: getting values in an array from dictionary

In my project i have an array which contains multiple dictionaries with some key values each. I want to get the all the value of "Link" key into an NSMutableArray.
the current array which contain dictionary is in the form of:
(
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
link = "https://player.vimeo.com/video/26186155";
title = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
};
},
{
YoutubeVideo = {
description = "What is endoscopic brain surgery";
link = "https://player.vimeo.com/video/16144037";
title = "What is endoscopic brain surgery";
};
},
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Block Injection pain management";
link = "https://player.vimeo.com/video/26186167";
title = "Cervical Spine Medial Branch Nerve Block Injection pain management";
};
},
{
YoutubeVideo = {
description = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
link = "https://player.vimeo.com/video/54275902";
title = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
};
},
{
YoutubeVideo = {
description = "Basic Shoulder Arthroscopy in Orthopaedics";
link = "https://www.youtube.com/embed/ywBVWIzGxtw";
title = "Basic Shoulder Arthroscopy in Orthopaedics";
};
}
i want to get all the values of link into a single array.
Currently the code i use which gives the following output is:
-(void)videolisting
{
NSString *post = #"api_key=bf45c093e542f057c123ae7d6";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://hChe/api/video"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
vidnamearray = [dict6 objectForKey:#"video"];
NSLog(#" Required Dir: %#",vidnamearray);
}
Try below solution
NSMutableArray *subArray=[[NSMutableArray alloc]init];
for(NSDictionary *dict in vidnamearray)
{
NSDictionary *subDict=[dict valueForKey:#"YoutubeVideo"];
[subArray addObject:[subDict valueForKey:#"link"]];
}
subArray will get all the values in the link key..!
Hope it helps you.....!
Try this
yourArr.valueForKeyPath("YoutubeVideo.link")
This will give the array containing all links.

IOS: Dictionary Return null value/Data

in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];

NSURLConnection to check periodic updates on the server

I have a function "downLoadButtonStatusSetter" which is called every 15 seconds with a timer.
It then calls sends "sendInstantGetInfoRequest" data to the server and checks whether the connection is available, and sets a flag.
The application is working properly, but gets into a busy state for a while when it fails to connect to the server.
How should i call these methods so that "It gets called every 15 seconds AND sets the flags even though it fails to connect to the server,
without affecting the main execution of the program. I have tried a combination of thread callings , but cannot, please help.
The timer calling code:
updateCheckTimer= [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(downLoadButtonStatusSetter) userInfo:nil repeats:YES];
ButtonStatusSetter Code:
-(BOOL) downLoadButtonStatusSetter
{
[self sendInstantGetInfoRequest];
if( instantGetInfoOffLineForButton)
{
//setbutton color etc....
}
}
-(NSArray *)sendInstantGetInfoRequest
{
NSString *getInfoURL=[SAGlobal getInfoURL];
NSArray *keys = [NSArray arrayWithObjects:#"username",#"password", nil];
NSArray *objects = [NSArray arrayWithObjects:SharedAppDelegatee.SAloginName, SharedAppDelegatee.SAloginPassword, nil];
jsonManager = [[JsonRequestManager alloc] init];
SAJSonResult* resultk=[jsonManager sendJsonAsPOSTData: keys AndValues:objects toURL: getInfoURL];
if(resultk.jsonError)
{
instantGetInfoOffLineForButton=true;
}
else{
instantGetInfoOffLineForButton=false;
}
return resultk.jsonResult;
}
The JSON request sending code:
-(SAJSonResult *) sendJsonAsPOSTData:(NSArray *) keys AndValues:(NSArray *) values toURL:(NSString *)anURL
{
////..................
NSURL *url1 = [NSURL URLWithString:anURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&jsonError];
if (jsonError) {
..............
return jResult;
}
else
{
...............
return jResult;
}
}
}

iOS : -[__NSCFDictionary _expandedCFCharacterSet]: error

I am working on iOS application.In one scenario I am sending phone number and some text message to server like this
- (void)postData:(NSString *)message :(NSString *)mobileno
{
NSLog(#"postData is called");
#try
{
NSString *urlString = [NSString stringWithFormat:#"http://anlgelist.commonshell.net/api/account"];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest *urlRequest1=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSMutableDictionary *postDictionary=[[NSMutableDictionary alloc]init];
[postDictionary setValue:message forKey:#"Message"];
[postDictionary setValue:mobileno forKey:#"MobileNumber"];
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSError *error = nil;
NSLog(#"~~~~~~~~ postDictionary is %#",postDictionary);
NSString * jsonDataString =[jsonWriter stringWithObject:postDictionary];
if ( ! jsonDataString )
{
NSLog(#"Error: %#", error);
}
NSData *requestData = [NSData dataWithBytes:[jsonDataString UTF8String] length:[jsonDataString length]];
[urlRequest1 setHTTPMethod:#"PUT"];
[urlRequest1 setValue:#"application/json" forHTTPHeaderField:#"content-type"];
[urlRequest1 setHTTPBody: requestData];
connection1 = [NSURLConnection connectionWithRequest:urlRequest1 delegate:self];
}
#catch (NSException *exception)
{
////NSLog(#"exception is %#",exception);
#throw exception;
}
}
I am continuously calling this web service to send the details.But sometimes I am getting the following error and app getting crashed.
<Error>: -[__NSCFDictionary _expandedCFCharacterSet]: unrecognized selector sent to instance 0x14fdf350
I had not faced this kind of error previously.I googled but not found the solution.
Crash Report is
I am not sure it will work fine, but in your case the object has released and you try to access that, So i have prefered this solution,please try this.
SBJsonWriter *jsonWriter = [[SBJsonWriter new]retain];

Need to have transaction id from pay key PayPal

I have successfully integrated PayPal into my iOS application using PayPal MPL library.
But the problem is how to get the transaction id from paykey which i get from callback method of PayPal.
i have tried this way but getting error of invalid request.
- (void)paymentSuccessWithKey:(NSString *)payKey andStatus:(PayPalPaymentStatus)paymentStatus
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://svcs.paypal.com/AdaptivePayments/PaymentDetails"]];
//NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails"]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:url];
NSString *parameterString = [NSString stringWithFormat:#"payKey=%#&requestEnvelope.errorLanguage=%#",payKey,#"en_US"];
NSString *msgLength = [NSString stringWithFormat:#"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
//do post request for parameter passing
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//passing key as a http header request
[theRequest addValue:api_username forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
//passing key as a http header request
[theRequest addValue:api_password forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[theRequest addValue:api_signature forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
[theRequest addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[theRequest addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[theRequest addValue:app_id forHTTPHeaderField:#"X-PAYPAL-APPLICATION-ID"];
[theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&err];
NSString* s = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *result = [s JSONValue] ;
}
i need to save the transaction id on the backend of my application for future references.
Need to know how to get it asap.
Any help would be appreciated.
Thanks & Regards
Pankaj
I dont know about iOS but for andorid , we implement PayPalResultDelegate , Serializable interface , in a class like . i am sharing my code :
class ResultDelegate implements PayPalResultDelegate, Serializable
{
private static final long serialVersionUID = 10001L;
PaypalDetailImplementation ob = new PaypalDetailImplementation() ;
public void onPaymentSucceeded(String payKey, String paymentStatus)
{
ob.resultTitle = "SUCCESS";
ob.resultInfo = "You have successfully completed your transaction.";
ob.resultExtra = "Key: " + payKey;
this.displayInformation("onPaymentSucceeded", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void onPaymentFailed(String paymentStatus, String correlationID,String payKey, String errorID, String errorMessage)
{
ob.resultTitle = "FAILURE";
ob.resultInfo = errorMessage;
ob.resultExtra = "Error ID: " + errorID + "\nCorrelation ID: "+ correlationID + "\nPay Key: " + payKey;
this.displayInformation("onPaymentFailed", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void onPaymentCanceled(String paymentStatus)
{
ob.resultTitle = "CANCELED";
ob.resultInfo = "The transaction has been cancelled.";
ob.resultExtra = "";
this.displayInformation("onPaymentCanceled", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void displayInformation ( String msg , String resultTitle , String resultInfo , String resultExtra )
{
Log.i("Result as message : ",msg);
Log.i(resultTitle,"tushar:onPaymentSucceeded");
Log.i(resultInfo,"tushar:onPaymentSucceeded");
Log.i(resultExtra,"tushar:onPaymentSucceeded");
}
First, it's critically important to make sure that you don't ship an app with the API password & signature. Otherwise a malicious user could disassemble your app, recover the credentials and perform arbitrary operations to your account. Read more about verifying a payment.
But, assuming that you implemented similar code on your server, it should work. What is the exact error that you're getting?
I got this problem solved my self.
I was making the X-PAYPAL-REQUEST-DATA-FORMAT of JSON type but when i changed it to NV i start edgetting transaction id.
Thanks to all for their answers.

Resources