I'm pretty new to Objective C in general...
I'm wondering how I can use a *variable in the view controller, and add it onto the web view URL. Bellow is a UIWebViewer, It loads "site.com/something.php"... Along with that I would like for it to addon to the URL "?uuid=(UUID Variable here)".
Sorry... I'm more used to PHP/Perl coding where you can just throw in "$uuid"...
Thanks,
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *UUID = [[NSUUID UUID] UUIDString];
NSURL *myURL = [NSURL URLWithString:#"http://www.site.com/something.php?uuid="];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[myWebView loadRequest:myRequest];
}
It's very simple you just need to create a property to assign whatever value you want to it
ViewController.m
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *uuid = [[NSUUID UUID] UUIDString]; // Convention says that UUID should uuid
// All we need to do now is add the uuid variable to the end of the string and we can do
// that by using stringWithFormat:
NSURL *myURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.site.com/something.php?uuid=%#", uuid]];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[myWebView loadRequest:myRequest];
}
Check the documentation of NSString and the class method stringWithFormat:
Here's what you're looking for:
NSString *UUID = [[NSUUID UUID] UUIDString];
NSString *urlstr = [NSString stringWithFormat:
#"http://www.site.com/something.php?=%#", UUID];
NSURL *myURL = [NSURL URLWithString:urlstr];
NSString's stringWithFormat: method allows you to build strings from literal strings and varaibles. Variables are added to the literal string using format specifiers. Most of the format specifiers are the same as all the other C-based languages, %d for integer types, %f for floating types, %c for char, etc.
In the case of Objective-C, the %# is used as the place holder for objects that respond to the description selector, which returns a string. (In the case of an NSString, it just returns the string itself, but you'll notice that you can put lots of other types of objects in here too... in fact, every object that inherits from NSObject has a default description method).
Related
I am making this chat app with works with a .php file on my webserver to store the data in a SQL db
Here is my code so far:
#import "vtchatViewController.h"
#interface vtchatViewController ()
#end
#implementation vtchatViewController
#synthesize messageBox, messageView, Send, Refresh;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *usrName = [[NSUserDefaults standardUserDefaults] stringForKey:#"user_name"];
NSURL *url = [NSURL URLWithString:#"http://server.com/ios/messages.php"]; [messageView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (IBAction)refreshButton:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://server.com/ios/messages.php"]; [messageView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (IBAction)sendButton:(id)sender {
// server.com/ios/add.php?user=Username here&message=Message Her
[messageBox resignFirstResponder];
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=",usrName "&message=%#", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];
[messageView loadRequest:[NSURLRequest requestWithURL:add]];
messageBox.Text = #"";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
However on the line "viewDidLoad" I can't get it to use the username from my settings bundle:
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=",usrName "&message=%#", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];
I get the error "Use of undeclared indentifier 'usrName' and also I have no idea if I did implent the "usrName" correct for use in this
I simply need it to send data to "server.com/ios/add.php?" where data should be in this format: "user=Username here&message=Message here"
I got it working if I just use a fixed username, but as said, I have no idea how to make the thing use the username stored in my settings file
Thanks in advance
You need to use string format tokens to get it to insert the username into the urlString variable like this:
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=%#&message=%#", usrName, messageBox.text];
That should help you understand why your format string wasn't working and why you were getting that error. My code above isn't escaping the values of usrName or messageBox.text so you'll need to add those back into your code.
you should let you usrName beacome like a interface variable.
like that:
#interface vtchatViewController () {
NSString *usrName;
}
#end
#implementation vtchatViewController
- (void)viewDidLoad
{
...
NSString *usrName = [[NSUserDefaults standardUserDefaults] stringForKey:#"user_name"];
...
}
#end
I'm calling a JSON URL from the NSURL class. My URL is:
like://Design_Time_Addresses/IServices/RoleService/json/Role/?name=%#",[textField text]];
When I write "doctor" in the textfield I have to get all the details of doctor through that URL. Similarly when I write "engineer" I have to get all the details of engineer. So it means what I type in the textfield, the name in URL should be replaced with the textfield value. But when I write the code like this:
NSURL *jsonUrl =[NSURL URLWithString:#"http://Design_Time_Addresses/ICloudServices/RoleService/json/Role/?name=%#",[textField text]];
NSString *jsonStr =[[NSString alloc] initWithContentsOfURL:jsonUrl];
NSMutableDictionary *jsonDetails = [[NSMutableDictionary alloc]initWithDictionary:[jsonStr JSONValue]];
As shown here I am using the NSURL class to get this URL.
I am getting an error in the NSURL class. How do I pass the text fields value to a URL?
First line should be
NSString *urlString = [NSString stringWithFormat:#"http://Design_Time_Addresses/ICloudServices/RoleService/json/Role/?name=%#",[textField text]];
NSURL *jsonUrl =[NSURL URLWithString:urlString];
NSURL URLWithString expects a single string argument, while you are providing two. Since you probably want to construct a single string from the #"http://..." string and [textField text], you should use an NSString method to concatenate them. You can't rely on NSURL to concatenate the string for you.
I have the following code that makes a Google Places API request. The parameters are statically set at the moment. How would I go about making those parameters (types and lat/lon and the Google Key - which I've defined as a constant in the .h file) objects instead?
My problem arises with the NSURL because I can't add format specifiers to it.
thanks for any help.
-(void)ParseXML_of_Google_PlacesAPI
{
NSURL *googlePlacesURL = [NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/xml?location=34.0522222,-118.2427778&radius=500&types=bar&sensor=false&key=MyGoogleAPIKey"];
NSData *xmlData = [NSData dataWithContentsOfURL:googlePlacesURL];
xmlDocument = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:nil];
NSArray *arr = [xmlDocument.rootElement elementsForName:#"result"];
for(GDataXMLElement *e in arr )
{
[placesOutputArray addObject:e];
}
Good ol' stringWithFormat?
`NSString* urlToCall = [NSString stringWithFormat:#"http:://url.to.webservice/api?param1=%#¶m2=%#", param1, param2]`
This may be helpful for you
float lat=34.0522222,lon=-118.2427778;
NSString *typestr=#"bar";
NSString *key=#"MyGoogleAPIKey";
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/xml?location=%f,%f&radius=500&types=%#&sensor=false&key=%#",lat,lon,typestr,key]];
NSLog(#"url values ==%#",url);
Format specifiers directly to NSURL like this:
NSURL *googlePlacesURL = [NSURL URLWithString:[NSString stringWithFormat:#"http:://url.to.webservice/api?param1=%#%param2=%#", param1, param2]];
I have a question related to reverse geo-coding.
In my app, I have some coordinates (not my current coordinates) and I want to convert them into placemarks. I've dug a lot of websites and codes but they are all about reverse geocoding of current location...
Is there any way to get placemarks of specified coordinates (which are not current location)?
And if there is, please help me with some code or references.
You can achieve this in two ways:-
First way:-
Get the info using google api
-(void)findAddresstoCorrespondinglocation
{
NSString *str = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",myCoordInfo.latitude,myCoordInfo.longitude];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setRequestMethod:#"GET"];
[request setDelegate:self];
[request setDidFinishSelector: #selector(mapAddressResponse:)];
[request setDidFailSelector: #selector(mapAddressResponseFailed:)];
[networkQueue addOperation: request];
[networkQueue go];
}
in response you will get all information about the location coordinates you specified.
Second Approach:-
Implement reverse geocoding
a.)add mapkit framework
b.)Make instance of MKReverseGeocoder in .h file
MKReverseGeocoder *reverseGeocoder;
c.)in .m file
self.reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:cordInfo];
reverseGeocoder.delegate = self;
[reverseGeocoder start];
Implement two delegate methods of MKReverseGeoCoder
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(#"MKReverseGeocoder has failed.");
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
MKPlacemark * myPlacemark = placemark;
NSString *city = myPlacemark.thoroughfare;
NSString *subThrough=myPlacemark.subThoroughfare;
NSString *locality=myPlacemark.locality;
NSString *subLocality=myPlacemark.subLocality;
NSString *adminisArea=myPlacemark.administrativeArea;
NSString *subAdminArea=myPlacemark.subAdministrativeArea;
NSString *postalCode=myPlacemark.postalCode;
NSString *country=myPlacemark.country;
NSString *countryCode=myPlacemark.countryCode;
NSLog(#"city%#",city);
NSLog(#"subThrough%#",subThrough);
NSLog(#"locality%#",locality);
NSLog(#"subLocality%#",subLocality);
NSLog(#"adminisArea%#",adminisArea);
NSLog(#"subAdminArea%#",subAdminArea);
NSLog(#"postalCode%#",postalCode);
NSLog(#"country%#",country);
NSLog(#"countryCode%#",countryCode);
}
I'm new in Objective C and I have some problem....
It's my code:
1)
testAppDelegate.h (not all):
#interface testAppDelegate : NSObject <NSApplicationDelegate> {
IBOutlet NSWindow *windowLogin;
IBOutlet NSWindow *windowContactList;
IBOutlet NSTextField *memStatus;
NSString *access_token, *expires_in, *user_id;
NSMutableArray *records;}
2) testAppDelegate.m (not all):
int posInStr(NSString *subString, NSString *genString){
NSRange match;
match = [genString rangeOfString:subString];
return match.location;
}
NSString* pars(NSString *str_,NSString *str,NSString *_str){
NSString *tmp;
int startPos = posInStr(str_,str) + [str_ length];
tmp = [str substringFromIndex:startPos];
int finishPos = posInStr(_str, tmp);
return [tmp substringToIndex:finishPos];
}
-(IBAction)but2Click: (id)sender{
NSString *tmp2 = access_token;
NSString *tmp = [NSString stringWithFormat:#"https://api.vkontakte.ru/method/messages.getDialogs?count=3&access_token=%#",tmp2];
NSURL *url = [NSURL URLWithString:tmp];
NSLog(#"%#",tmp);
NSLog(#"%#",url);
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(showLoaded)];
[request startAsynchronous];
}
-(IBAction)but1Click:(id) sender{
NSURL *url = [NSURL URLWithString:#"http://api.vkontakte.ru/oauth/authorize?client_id=293&scope=friends,messages&redirect_uri=http://api.vkontakte.ru/blank.html&display=popup&response_type=token"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinishedtest:)];
[request startAsynchronous];
}
- (void)requestFinishedtest:(ASIHTTPRequest *)request
{
[memStatus setStringValue:#"Loading..."];
NSString *tmp = [NSString stringWithFormat:#"%#",[request url]];
[tmp retain];
access_token = pars(#"access_token=", tmp, #"&");
NSLog(#"%#",access_token);
expires_in = pars(#"expires_in=", tmp ,#"&");
user_id = pars(#"user_id=", [NSString stringWithFormat:#"%#&",tmp], #"&");
[memStatus setStringValue:#"Logined"];
[windowLogin orderOut:nil];
[windowContactList makeKeyAndOrderFront:self];
[NSApp activateIgnoringOtherApps:YES];
}
My problem:
"EXC_BAD_ACCESS" in "but2Click"
You are assigning an autoreleased object here:
access_token = pars(#"access_token=", tmp, #"&");
access_token must be getting released before the but2click method is invoked by a button tap.
You need to retain it if you want to use it later.
It's going to be really hard to figure this out from code -- you are going to have to debug it.
I wrote this blog to help understand and debug EXC_BAD_ACCESS
Basically, you are dereferencing a pointer that is pointing to memory that isn't allocated to your process. The main reasons that this could happen are
You are using an object that has been deallocated
The heap is corrupt
The things you should do to debug this:
Do a Build and Analyze. The reports of leaks are bad, but not related to this issue -- you want to look for issues of too few retains
Turn on Zombies and run in the debugger. Now, none of your objects will be deallocated, but when they have a retain count 0, they will complain to the debugger if you use them.
There are other tips on the blog that are a little harder to explain