In my iOS app I've to parse a JSON file. From this JSON I need the following stuff: name, image width and image height. To get image name I'ven't any problem, to get image with and height I use the following code:
- (void) loadImageFromWeb:(NSString *)urlImg forName:(NSString*)name {
NSURL* url = [NSURL URLWithString:urlImg];
//NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *authCredentials =#"reply:reply";
NSString *authValue = [NSString stringWithFormat:#"Basic %#",[authCredentials base64EncodedStringWithWrapWidth:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
imageWidth = image.size.width;
imageHeight = image.size.height;
imgWidth = [NSString stringWithFormat:#"%f", imageWidth];
imgHeight = [NSString stringWithFormat:#"%f", imageHeight];
self.dictWithDataForPSCollectionView = #{#"title": name,
#"width": imgWidth,
#"height": imgHeight};
[self.arrayWithData addObject:self.dictWithDataForPSCollectionView];
NSLog(#"DATA ARRAY: %#", self.arrayWithData);
} else {
NSLog(#"ERRORE: %#", error);
}
}];
}
You can see that I save the name, image width and image height in a NSDictionary then I put this in an NSMutableArray. When it execute the NSLog, I see this:
DATA ARRAY: (
{
height = "512.000000";
title = "Eau de Toilet";
width = "320.000000";
},
{
height = "1049.000000";
title = "Eau de Toilet";
width = "1405.000000";
}
)
My question is how to get this information back in the class who call my json parser, I tried to access to the variable in this way:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
recivedData = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[recivedData appendData:data];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#", string);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *json;
NSError *err;
json = [NSJSONSerialization JSONObjectWithData:recivedData options:NSJSONReadingMutableLeaves error:&err];
JsonCategoryReader *reader = [[JsonCategoryReader alloc]init];
[reader parseJson:json];
}
But when I run the code it shows me an empty array. How I can have the information in this class?
UPDATE:
The JSON I've to parse is the following:
{
"1":{
"entity_id":"1",
"type_id":"simple",
"sku":"EAU_DE_TOILET_1",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/p\/r\/product_100ml.png"
},
"2":{
"entity_id":"2",
"type_id":"simple",
"sku":"EAU_DE_TOILET_2",
"description":"A passionate scent with the zest of exclusive Zegna Bergamot, sparked by Violettyne Captive, and the warmth of Vetiver and Cedarwood",
"short_description":"EAU DE TOILETTE NATURAL SPRAY",
"meta_keyword":null,
"name":"Eau de Toilet",
"meta_title":null,
"meta_description":null,
"regular_price_with_tax":60,
"regular_price_without_tax":60,
"final_price_with_tax":60,
"final_price_without_tax":60,
"is_saleable":true,
"image_url":"http:\/\/54.204.6.246\/magento8\/media\/catalog\/product\/cache\/0\/image\/9df78eab33525d08d6e5fb8d27136e95\/s\/c\/scheda_non_shop.jpg"
}
}
My method parseJson do the following:
- (void)parseJson:(NSDictionary *)jsonDict {
// Controllo che il json sia stato ricevuto
if (jsonDict) {
self.nameArray = [[NSMutableArray alloc]init];
self.imgUrlArray = [[NSMutableArray alloc]init];
self.dictWithDataForPSCollectionView = [[NSDictionary alloc]init];
self.arrayWithData = [[NSMutableArray alloc]init];
[self createArrayWithJson:jsonDict andIndex:1];
[self createArrayWithJson:jsonDict andIndex:2];
}
- (void)createArrayWithJson:(NSDictionary*)json andIndex:(NSString*)i {
NSDictionary *products = [json objectForKey:i];
NSString *name = [products objectForKey:#"name"];
NSString *imgUrl = [products objectForKey:#"image_url"];
// Scarico l'immagine e calcolo le dimensioni
if (name != nil && imgUrl != nil) {
[self loadImageFromWeb:imgUrl forName:name];
}
}
I hope you understand what I did
what happen is that your class is make before that your json is download, for have a good sequence you have to call your method for parse the json inside the completionHandler block, when you are sure that it is download. then when you have your object load you can parse it like this example:
for (NSDictionary *dic in reader.arrayWithData){
NSLog("height: %#",[dic objectForKey:#"height"]);
NSLog("title: %#",[dic objectForKey:#"title"]);
NSLog("width: %#",[dic objectForKey:#"width"]);
}
Related
I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};
Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.
Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else
{
return jsonObject;
}
}
I get the following _downloadedData:
<!-- pageok -->
<!-- managed by puppet -->
<html>
<pre>pageok</pre>
</html>
When using the code listed below:
- (void)downloadItems
{
//Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://www.scratchclass.com:80/videos/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:jsonFileUrl];
[request setHTTPMethod:#"GET"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"gzip" forHTTPHeaderField:#"Content-Encoding"];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(!connection){
NSLog(#"Connection Failed");
}
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse: %#",response);
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
NSString* newStr = [[NSString alloc] initWithData:_downloadedData encoding:NSUTF8StringEncoding ];
NSLog(#"didReceiveData: %#",newStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the videos
NSMutableArray *_videos = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new video object and set its props to JsonElement properties
GetVideos1 *testVideo = [[GetVideos1 alloc] init];
testVideo.IDVideo = jsonElement[#"IDVideo"];
testVideo.title = jsonElement[#"title"];
// Add this question to the locations array
[_videos addObject:testVideo];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_videos];
}
}
json is actually:
[{"IDVideo":"6Joup252fR0","title":"Top 30 Baseball
Plays"},{"IDVideo":"aAy3Sh_RXjc","title":"MLB top
plays"},{"IDVideo":"bkiaAGOoLjc","title":"Top 50 most unforgettable
ejections"}]
But I cannot get to the data as it is part of the #text node name. How can I fetch the data?
Here is the php code that was used:
<?php
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Constructor - open DB connection
function __construct() {
$this->db = new mysqli('idirectorySQL.db.9960960.hostedresource.com', 'idirectorySQL', 'iDirectory70!', 'idirectorySQL');
$this->db->autocommit(FALSE);
}
$con=mysqli_connect('idirectorySQL.db.9960960.hostedresource.com', 'idirectorySQL', 'iDirectory70!', 'idirectorySQL');
// This SQL statement selects ALL from the table 'videos'
$sql = "SELECT IDVideo,title FROM videos";
// Check if there are results
if ($result = mysqli_query($con, $sql)) {
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object()) {
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Close connections
mysqli_close($con);
// Finally, encode the array to JSON and output the results
header('Content-type: application/json');
// echo json_encode($resultArray, JSON_PRETTY_PRINT);
echo json_encode($resultArray);
}
?>
I used
header('Content-type:application/x-www-form-urlencoded')
but I still received the same message. Also, this is what reads from the request headers:
Accept text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Don't set any custom parameters in the NSURLRequest, GET is the default anyway.
As NSURLConnection is deprecated, this is a solution with the recommended NSURLSession API
NSURL *url = [NSURL URLWithString:#"http://www.scratchclass.com:80/videos/"];
NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
if (error) {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
} else {
NSError *jsonError;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog(#"NSJSONSerialization failed! Error - %# %#",
[jsonError localizedDescription],
[[jsonError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
} else {
NSMutableArray *videos = [[NSMutableArray alloc] init];
for (NSDictionary *item in jsonArray) {
GetVideos1 *testVideo = [[GetVideos1 alloc] init];
testVideo.IDVideo = item[#"IDVideo"];
testVideo.title = item[#"title"];
// Add this question to the locations array
[videos addObject:item];
}
if (self.delegate) {
[self.delegate itemsDownloaded:videos];
}
}
}
}] resume];
I'm trying to get Title data from the server but unfortunately I'm getting nothing as it is shown in the NSLog below. Shouldn't I get the Title dictionary? Please where would be my issue?
While I want to set that data in the UITableVeiw
- (void)getNews{
NSURL *url = [NSURL URLWithString:#"http://www.example.ashx"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *getData = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if([[[getData objectForKey:#"Success"] stringValue] isEqualToString:#"1"]){
[dataNewsArray addObjectsFromArray:[[greeting objectForKey:#"Response"] objectForKey:#"Datasource"]];
}
NSDictionary *aDict = [NSDictionary dictionaryWithObject:dataHaberlerArray forKey:#"Title"];
NSLog(#"Check %#", aDict);
}
}];
}
NSLog result as like this;
Check {
Title = (
{
Content = "";
Date = "13.10.2014";
Time = "01:17:34";
Title = "example";
},
NSLog for dataNewsArray
2014-10-13 13:40:14.828 new_8[8742:346345] Check (
{
Content = " ";
Date = "13.10.2014";
Time = "01:38:53";
Title = "*test*";
},
write the below code to get one title
[[[aDict objectForKey:#"Title"] objectAtIndex:0] objectForKey:#"Title"]];
for all the titles use the below code
NSMutableArray *titleArray = [[NSMutableArray alloc] init];
for (int i=0; i<[[aDict objectForKey:#"Title"] count]; i++) {
[titleArray addObject:[[[aDict objectForKey:#"Title"] objectAtIndex:i] objectForKey:#"Title"]];
}
The above solution provide the answer, but there is some other way using predicate to get the data
I am using a button action to update the value of a MySQL table field. The update is perform in the web server, but I need to update a UILabel text in my view Controller.
This is the code I have implemented:
- (IBAction)votarAction:(id)sender {
//URL definition where php file is hosted
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *string = [NSString stringWithFormat:#"%d", categoriaID];
NSLog(#"ID EMPRESA %#",string);
NSMutableString *ms = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[ms appendString:string];
// URL request
NSLog(#"URL = %#",ms);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
//URL connection to the internet
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
//update your label
});
});
}
#pragma NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//buffer is the object Of NSMutableData and it is global,so declare it in .h file
buffer = [NSMutableData data];
NSLog(#"ESTOY EN didReceiveResponse*********");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"ESTOY EN didReceiveDATA*********");
[buffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Here You will get the whole data
NSLog(#"ESTOY EN didFINISHLOADING*********");
NSError *jsonParsingError = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&jsonParsingError];
//And you can used this array
NSLog(#"ARRAY = %#",array);
//HERE LABEL.TEXT UPDATE CODE
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR de PARSING");
NSLog(#"ESTOY EN didFAILWITHERROR*********");
}
As I told you, the field value at the MySQL table is updated every time the button is tapped, but the problem is that the NSURLConnection delegate methods are never called.
Any help is welcome
In your view controller's header file add: <NSURLConnectionDelegate>
Also, there's no need to throw the NSURLConnection into a seperate background process, maybe that's why the delegates aren't called. NSURLConnection is already asynchronous
Perhaps try something like this:
- (IBAction)votarAction:(id)sender
{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *originalString = [NSString stringWithFormat:#"%d", categoriaID];
NSMutableString *mutablesString = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[mutableString appendString:originalString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mutableString]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_async(dispatch_get_main_queue(), ^
{
// Update your label
self.label.text = [array objectAtIndex:someIndex];
});
}
else
{
// Tell user there's no internet or data failed
}
}];
}
I am using Bing Search API and able to successfully parse the xml but not JSON.Below is the code to both parse xml and JSON,when I nslog the output of the JSON it shows "null" I don't know how to proceed from here.
-(void)searchBing:(NSString *)text{
//NSString *query1 = #"San Francisco Baseball";
NSString *query = [NSString stringWithFormat: #"'%#'",text];
//NSString *query = query1;
NSString *format = #"atom";
NSString *market = #"'en-us'";
//NSInteger top = 2;
NSMutableString *fullURL = [NSMutableString stringWithCapacity:256];
[fullURL appendString:URL];
[fullURL appendFormat:#"Web?$format=%#", format];
[fullURL appendFormat:#"&Query=%#",
[query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[fullURL appendFormat:#"&Market=%#",
[market stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [fullURL appendFormat:#"&$top=%d", top];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:
[self getRequest:fullURL] delegate:self];
if (connection)
{
NSLog(#"Connection established");
}
else
{
NSLog(#"Connection failed");
}
}
Below where am parsing both xml(successful) and JSON(unsuccessful)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// convert to JSON
NSLog(#"Finished loading: Received %d bytes of data",[self.responseData length]);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
[parser setDelegate: self];
[parser parse];
NSLog(#"XMl == %#",parser);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog(#"json data = %#",res);//getting null
}
Am using Base_64 encoding and to all viewers nothing wrong with query because getting correct information via xml parser.But I want response in JSON.
Structure sample
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"testign"
},
"Spell":{
"Total":1,
"Results":[
{
"Value":"testing"
}
]
},
"Web":{
"Total":5100,
"Offset":0,
"Results":[
{
"Title":"Testign part 2 - Tiernan OTooles Programming Blog",
"Description":"If this works, it means nothing really, but i have managed to build a .TEXT blog posting app. could be handy if i move my main blog to .TEXT, which i am thinking about..",
"Url":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DisplayUrl":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DateTime":"2008-10-21T05:08:05Z"
}
]
}
}
}
From your post:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
It looks like you're trying to use the same data as XML and JSON. You can't do that. The data returned from the server is in one form OR the other. It won't be both.