Trouble Storing URL in NSURL Variable - objective-c

At the end of this method, "address" (NSURL variable) returns nil, even though "countyName" returns #"Alameda". What am I doing wrong?
-(void) getDataUrl {
if ([countyName isEqual: #"Alameda"]) {
NSURL * fileURL = [[NSURL alloc] initWithString:#"http://www.myservername.com/alameda.php"];
self.address = fileURL;
}
if ([countyName isEqual: #"Napa"]) {
NSURL * fileURL = [[NSURL alloc] initWithString:#"http://www.myservername.com/napa.php"];
self.address = fileURL;
}
if ([countyName isEqual: #"San Luis Obispo"]) {
NSURL * fileURL = [[NSURL alloc] initWithString:#"http://www.myservername.com/sanluisobispo.php"];
self.address = fileURL;
}
}

The solution here was to create a plist containing an array of dictionaries. Each dictionary held the name of a county and a url for the php script for that county. The plist was used to populate a tableview, and then the selected row was pushed to another tableview using the variable "countyName". "countyName" held the county name and the url. I then used countyName in my retrieveData method like this:
NSURL *url = [NSURL URLWithString:[countyName valueForKey:#"weburl"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Thanks to everyone for taking the time to respond.

Related

objective c how create new playlist on SoundCloud?

Trying to create new playlist, but it doesn't work.
Function for request:
-(NSURLRequest *)makeNewPlaylistsRequestNamed:(NSString *)name
{
NSURL *url = [NSURL URLWithString:#"https://api.soundcloud.com/playlists"];
NSURLComponents *comp = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:YES];
NSMutableArray *qi = [[NSMutableArray alloc] init];
[qi addObject:[NSURLQueryItem queryItemWithName:#"oauth_token" value:self.authResult.value]];
comp.queryItems = qi;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comp.URL];
request.HTTPMethod = #"PUT";
NSDictionary *newPL = #{#"title":name,#"sharing":#"public",#"tracks":#[]};
NSDictionary *gistDict = #{#"playlist":newPL};
NSError *jsonError;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:gistDict
options:NSJSONWritingPrettyPrinted
error:&jsonError];
[request setHTTPBody:jsonData];
return request;
}
But new playlist doesn't creates.
I used web API - https://developers.soundcloud.com/docs/api/reference#playlists

TBXML with NSData in Xcode

I have a URL that returns a pretty flat XML file: <entries><title>val1</title><author>Bob</author></entries> The code runs ok:
NSString *urlString = [NSString stringWithFormat:#"http://www.somesite.php?qid=%d", __inum];
NSLog(#"urlString = %#", urlString);
NSURLResponse * response = nil;
NSError * error = nil;
NSURLRequest * urlRequest = [NSURLRequest requestWithURL: [NSURL URLWithString:urlString]];
NSData * myData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSLog(#"%#", myData);
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:nil];
TBXMLElement *rootElement = sourceXML.rootXMLElement;
if (rootElement) {
NSLog(#"Root element found...");
TBXMLElement *qaElement1 = [TBXML childElementNamed:#"title" parentElement:rootElement];
if (qaElement1) {
NSString *idAttribute = [TBXML valueOfAttributeNamed:#"title" forElement:qaElement1];
NSLog(#"Got to the 1st call for idAttribute... %#", idAttribute);
}
else { NSLog(#"There is no value for title..."); }
}
else { NSLog(#"Root element must be null..."); }
}
It finds the root element and gets to the call for valueOfAttribute:#"title" but the value is always (null).
So my question: do I have to do something to convert the NSData back to man readable (I was under the impression TBXML gave that option to work with the NSData and did the calculation). If not, what is the call to create (and then use) an NSString in UTF8 from 'myData'?
what is the call to create (and then use) an NSString in UTF8 from 'myData'?
use initWithData:encoding:
NSString *str = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
or stringWithUTF8String: if you know myData is null-terminated UTF8 string
NSString *str = [NSString stringWithUTF8String:[myData bytes]];
Do not ignore error.
NSError *error = nil;
TBXML *sourceXML = [[TBXML alloc] initWithXMLData:myData error:&error];
if (error) {
// handle it, at least log it
}

Converting JSON Result as an Array

I have this JSON data :
array: {
data = (
{
"com_id" = 1;
"com_name" = Apple;
},
{
"com_id" = 2;
"com_name" = "Google";
},
{
"com_id" = 3;
"com_name" = "Yahoo";
}
);
message = "Data found";
response = success;
}
here's my code to fetch that data :
NSURL * url = [[NSURL alloc] initWithString:#"https://jsonurlhere.com"];
// Prepare the request object
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Prepare the variables for the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a Array around the Data from the response
NSArray* object = [NSJSONSerialization
JSONObjectWithData:urlData
options:0
error:&error];
NSLog(#"array: %#", object);
now, I want to use that JSON data into my PickerView. how to change that JSON data into array so that I can load it to replace my existing array (self.nameCompany)?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.nameCompany = #[#"Apple", #"Google", #"Yahoo"];
}
I think It's helpful to you. Can you try this following link? It's not use to any supporting files. Also, see this link NSJSONSerialization supported URL
NSJSONSerialization
check this code , your response is not a array but Dictionary.
-(void)loadData{
NSURL * url = [[NSURL alloc] initWithString:#"https://jsonurlhere.com"];
// Prepare the request object
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Prepare the variables for the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a Array around the Data from the response
NSDictionary* object = [NSJSONSerialization
JSONObjectWithData:urlData
options:0
error:&error];
NSLog(#"array: %#", [object objectForKey:#"data"]);
NSMutableArray *companyArray=[[NSMutableArray alloc] init];
for (NSDictionary *tempDict in [object objectForKey:#"data"]) {
[companyArray addObject:[tempDict objectForKey:#"com_name"]];
}
self.nameCompany=[NSArray arrayWithArray:companyArray];
}

NSURLConnection (Syncronous Request) returns (null)

I want to get HTML from website. I wrote below code but this returns (null).
NSString *strURL = #"http://www.googole.com";
- (NSString *)getHtml
{
NSURL *url = [NSURL URLWithString: strURL];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest : req
returningResponse : &response
error : &error];
NSString *strData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return strData;
}
I think you have mistyped the url.
It should be NSString *strURL = #"http://www.google.com";

Want to split the JSON from the URL not the response

I want to split the json part from this URL in my iPhone application.
http://vkontakte.ru/login_success.html#session={"expire":"1272008089","mid":"100172","secret":"9c8d8f0305","sid":"1131703552161ae352a1256402e3140d7cbde41b1602a93d15472c82"}
I tried and and saved the JSON into a NSString but what i am getting is
http://vkontakte.ru/api/login_success.html?session=%7B%22mid%22:113158415,%22secret%22:%227ce58bfcd3%22,%22sid%22:%2203831b43c1bb992f9477efbfe96e83f6ecff1c1b661315ac0a20719cf57a44%22,%22expire%22:0%7D
This is not coming in JSOn Format. Below is my code
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSError* error;
NSLog (#"json path %#",url);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];
NSString *json_string = [url absoluteString];
NSArray *arr = [json_string componentsSeparatedByString:#"="];
json_string = [arr objectAtIndex:1];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [json_string JSONValue];
NSLog(#"%#",error);
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"secret "], [[status objectForKey:#"mid"] objectForKey:#"sid"]);
}
return YES;
}
How can move further?
Try replacing:
NSString *json_string = [url absoluteString];
with
NSString *json_string = [[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];.
That's a really strange thing you're doing, though. Why does the URL have JSON in it?