I'm using the camfind api, I post a request where I send the api an image and get a token, and then I can use the token to get what the image is, but this takes two steps, a post and a get request. I want to combine them, so the get request auto fires right when the server responds to the post request. Here is the code :
I specify a value for the token at the top
NSString *tokenValue;
the request method, here an image is selected and sent to the server, the server sends a token response back in this request
- (void *) requestMethod: (UIImage *)imageToConvert{
NSString *temp = #"saved";
NSLog(#"%#", temp);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [paths objectAtIndex:0];
NSString *imagePath = [documentDirectoryPath stringByAppendingPathComponent:#"tmp_image.jpg"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
NSData *imageData = UIImageJPEGRepresentation(imageToConvert , 1.0);
[imageData writeToURL:imageURL atomically:YES];
// NSString *base64image = [NSString stringWithFormat:#"%#",[imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]];
NSString *base64image = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
// These code snippets use an open-source library.
// NSString *baseboy = [base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSURL *urlimage_request = [NSURL URLWithString:[base64image stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *headers = #{#"X-Mashape-Key": #"********"};
NSDictionary *parameters = #{#"focus[x]": #"480", #"focus[y]": #"640", #"image_request[altitude]": #"27.912109375", #"image_request[image]": imageURL, #"image_request[language]": #"en", #"image_request[latitude]": #"35.8714220766008", #"image_request[locale]": #"en_US", #"image_request[longitude]": #"14.3583203002251"};
UNIUrlConnection *asyncConnection = [[UNIRest post:^(UNISimpleRequest *request) {
[request setUrl:#"https://camfind.p.mashape.com/image_requests"];
[request setHeaders:headers];
[request setParameters:parameters];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSString *token = response.description;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
for(NSString *key in [json allValues])
{
tokenValue = [json valueForKey: #"token" ];
NSString *two = [json valueForKey: #"token" ]; // assuming the value is indeed a string
NSLog(#"Token :%#", two);
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, two];
// NSString *responseURL = [one stringByAppendingString:two];
NSLog(#"response URL %#", responseString);
// UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
// [request setUrl:responseString];
// [request setHeaders:headers];
// }] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
// NSInteger code = response.code;
// NSDictionary *responseHeaders = response.headers;
// UNIJsonNode *body = response.body;
// NSData *rawBody = response.rawBody;
// NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
// options:kNilOptions
// error:nil];
// NSLog(#"Response status: %ld\n%#", (long) response.code, json);
//
//
// // NSLog(#"didfinishLoadingbody%#",rawBody);
// // NSLog(#"didfinishLoadingbody%#",body);
// //
// // NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// // NSLog(#"didfinishLoading tok%#",token);
// }];
}
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
// NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
the response method below uses the token from the request above to print out what the image is
- (void *) responseMethod {
// These code snippets use an open-source library.
NSString *one = #"https://camfind.p.mashape.com/image_responses" ;
NSString *responseString = [NSString stringWithFormat:#"%#/%#", one, tokenValue];
NSDictionary *headers = #{#"X-Mashape-Key": #"9hcyYCUJEsmsh4lNTgpgVX1xRq0Ip1uogovjsn5Mte0ONVBtes", #"Accept": #"application/json"};
UNIUrlConnection *asyncConnection = [[UNIRest get:^(UNISimpleRequest *request) {
[request setUrl:responseString];
[request setHeaders:headers];
}] asJsonAsync:^(UNIHTTPJsonResponse *response, NSError *error) {
NSInteger code = response.code;
NSDictionary *responseHeaders = response.headers;
UNIJsonNode *body = response.body;
NSData *rawBody = response.rawBody;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response.rawBody
options:kNilOptions
error:nil];
NSLog(#"Response status: %ld\n%#", (long) response.code, json);
// NSLog(#"didfinishLoadingbody%#",rawBody);
// NSLog(#"didfinishLoadingbody%#",body);
//
NSLog(#"didfinishLoading responseheader%#",responseHeaders);
// NSLog(#"didfinishLoading tok%#",token);
}];
return (__bridge void *)(self);
}
rest of the vc other stuff
-(void)loadView {
[super loadView];
}
- (void)viewDidLoad{
[super viewDidLoad];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
}
I don't know how to make the response method fire right away when the server replies, I don't know objc, im using this in a swift project
#end
Related
Basically I got response from server side and then i saved it in local file.Actually I fetched the response from server side and then saved into documents directory ,and now trying to fetch but it comes in NSString only ,i unable to get in NSDictionary....Here is following code
- (IBAction)loginButtonPressed:(id)sender
{
NSString *URLString = #"http://localhost/rest/login";
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"username": userNameTxtField.text, #"password": pwdTextField.text};
NSLog(#"Parameters:\n%#",params);
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
{
NSLog(#"Successfully Login ....: %#", responseObject);
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [NSString stringWithFormat:#"%#/sample.json", documents];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
NSError *writeError = nil;
NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];
if ((bytesWritten = 0))
{
NSLog(#"Error writing JSON Data");
}
else{
NSLog(#"Sucessfuly saved data...");
}
[stream close];
NSLog(#"path is :%#",path);
} failure:^(NSURLSessionDataTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
- (IBAction)fetch:(id)sender
{
NSError *deserializingError;
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"vaues are:%#",dict);
}
Your response object should be a type of NSDictionary. Therefore you can use its writeToFileAtPath method to save it to your documents directory.
When recreating the dictionary, you can use the NSDictionary's alloc and initWithContentsOfFile method to directly create a NSDictionary instance.
There are tons of posts on how to do that if you do a little Google search!
Try this!! It's working fine.
NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
[testStore setObject:#"vignesh" forKey:#"username"];
[testStore setObject:#"password" forKey:#"password"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(#"Got an error: %#", error);
jsonString = #"";
}
[self writeStringToFile:jsonString];
NSLog(#"Your JSON String is %#", [self readStringFromFile]);
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// Write to file
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// read from file
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;
#implementation DatabaseOperation
#synthesize databasePath;
+(DatabaseOperation*)sharedInstances{
if(!_sharedInstances){
_sharedInstances =[[super allocWithZone:nil]init];
}
return _sharedInstances;
}
+(id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstances];
}
-(id)init{
NSLog(#"Only first time Instances using Singleton:");
self =[super init];
if(self){
[self CreateDbpath];
}
return self;
}
-(BOOL)CreateDbpath{
NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];
self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:#"Mindset.sqlite"]];
NSFileManager *flg = [NSFileManager defaultManager];
BOOL isSuccess = false;
if([flg fileExistsAtPath:databasePath]==NO){
char *ermsgss = nil;
char const *dbpathss =[self.databasePath UTF8String];
if(sqlite3_open(dbpathss, &studs)==SQLITE_OK){
char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";
if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK){
NSLog(#"Failed to create table:");
}
else{
NSLog(#"Successfully to create table:");
}
}
sqlite3_close(studs);
}
return isSuccess;
}
-(void)insertDatabaseValue:(DataManagers *)getInserted{
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery=[[NSString alloc]initWithFormat:#"insert into emp values(?,?,?)"];
const char *_sqlQuery=[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);
NSData *jpegData =[[NSData alloc]init];
NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);
UIImage *imgesData =[UIImage imageWithData:imgeData];
CGRect rect = CGRectMake(0, 0, 185, 150);
UIGraphicsBeginImageContext(rect.size);
[imgesData drawInRect:rect];
UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
;
UIGraphicsEndImageContext();
jpegData = UIImageJPEGRepresentation(img, 0.01f);
sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);
if(sqlite3_step(ermsg)==SQLITE_DONE){
NSLog(#"Successfully inserted into db:");
}
else {
NSLog(#"Error %s",sqlite3_errmsg(studs));
}
}
sqlite3_close(studs);
sqlite3_finalize(ermsg);
}
}
-(NSMutableArray*)getAllData {
NSMutableArray *array =[[NSMutableArray alloc]init];
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery =[[NSString alloc]initWithFormat:#"select * from emp"];
const char *_sqlQuery =[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
while (sqlite3_step(ermsg)==SQLITE_ROW) {
DataManagers *mgr =[[DataManagers alloc]init];
NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;
mgr.userName = _Firstname;
NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;
mgr.cityName = lastName;
int imgBytes = sqlite3_column_bytes(ermsg, 2);
UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];
mgr.profileImg = img;
[array addObject:mgr];
}
}
}
return array;
}
Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}
Cannot encode the data in ios which fetch from webservice.
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[NSString stringWithFormat:#"%#",[dictionary objectForKey:key]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [[NSString stringWithFormat:#"%#",key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
It seems you are encoding NSDictionary and generate a NSString. And again Encoding that NSString and returns it.
You may do it in easy way as below.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
You may return above jsonData in your function to achieve your requirement as below.
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
return jsonData;
}
}
I am using php to get json data and here is response.
{"array":[{"Category":{"charity_id":"2","charity_name":"GiveDirectly","charity_amt":"0.20"}}]}
and here is my Objective-c code
NSError *err;
NSURL *url=[NSURL URLWithString:#"url"];
NSURLRequest *req=[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
if ([json isKindOfClass:[NSDictionary class]]){
NSArray *yourStaffDictionaryArray = json[#"array"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
for(NSDictionary *dict in dictionary[#"Category"]){
NSLog(#"%#",[[((NSString*)dict) componentsSeparatedByString:#"="] objectAtIndex:0] );
}
}
}
}
But this only returns the name's not the value. I have searched most of the question on this site but nothing helped be. Please help me i am new to iOS.
Thanks
Dictionary output is
{
"charity_amt" = "0.20";
"charity_id" = 2;
"charity_name" = GiveDirectly;
}
You don't need to do ComponentSeparatedByString. Once you get the NSDictionary for #"Category", you can get its value by using its keys.
Something like
if ([json isKindOfClass:[NSDictionary class]]){
NSArray *yourStaffDictionaryArray = json[#"array"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
NSDictionary *dict = dictionary[#"Category"];
NSLog(#"%#",dict[#"charity_id"]);
}
}
}
Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array
NSURL *url=[NSURL URLWithString:#"Your JSON URL"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = json[#"array"];
for(NSMutableDictionary *dic in array)
{
NSLog(#"%#",dic[#"Category"][#"charity_id"]); // prints 2
NSLog(#"%#",dic[#"Category"][#"charity_name"]); // GiveDirectly
NSLog(#"%#",dic[#"Category"][#"charity_amt"]); // 0.20
}
this is my parser json data, it's demo
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *urlString = #"https://api.foursquare.com/v2/venues/search?categoryId=4bf58dd8d48988d1e0931735&client_id=TZM5LRSRF1QKX1M2PK13SLZXRXITT2GNMB1NN34ZE3PVTJKT&client_secret=250PUUO4N5P0ARWUJTN2KHSW5L31ZGFDITAUNFWVB5Q4WJWY&ll=37.33%2C-122.03&v=20140118";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *string = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
[self parser:data];
}];
}
- (void)parser:(NSData *)data
{
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[obj enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
}];
}];
}
I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
To convert the data, I am using:
- (NSDictionary *)downloadPlist:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (!err) {
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];
if (!errorDescription)
return samplePlist;
[errorDescription release];
}
return nil;
}
Can anyone please tell me how to do that?
or this:
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];
Try this code:
NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", #"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"Login" ofType:#"plist"];
[dictionary writeToFile:path atomically:YES];
//here Login is the plist name.
Happy coding