I wanted to ask if anyone could help he get this code to work. Nothing is showing up in my MySQL database. Thanks, enbr.
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://mysite.come/myapp/submitrating.php?name=%#&comment=%#&rating=%#",
[selectedItem objectForKey:#"name"], comment.text, selectedRating];
NSString *urlstrEncoded = [urlstr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlstrEncoded];
[urlstr release];
[url release];
You need to do much more than that! At minimum you need the following:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
along with implementing the following methods:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
You're not doing anything with the URL object except creating it. Perhaps you want to try an NSURLConnection?
I got it to work with this code.
NSString *urlstr = [NSString stringWithFormat:#"http://mysite.com/myapp/submitrating.php?name=%#&comment=%#&rating=%#", [selectedItem objectForKey:#"name"], comment.text, selectedRating];
NSString *urlEncoded = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlEncoded];
NSString *ans = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
Related
I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.
Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..
NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];
To improve the secure , you may use the Http Basic Authentication.
There are answer here.
First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];
the search bar in Xcode 4.5.1 crashes when i type something, and it worked just fine when i was using Xcode 4.4
please help
i used this code which was an answer for another question, and it worked just fine when i was using Xcode 4/4, until i updated it to 4.5.1
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar{
//Perform the JSON query.
[self searchCoordinatesForAddress:[theSearchBar text]];
//Hide the keyboard.
[theSearchBar resignFirstResponder];}
-(void) searchCoordinatesForAddress:(NSString *)inAddress{
NSMutableString *urlString = [NSMutableString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#&output=json",inAddress];
//Replace Spaces with a '+' character.
[urlString setString:[urlString stringByReplacingOccurrencesOfString:#" " withString:#"+"]];
NSURL *url = [NSURL URLWithString:urlString];
//Setup and start an async download.
//Note that we should test for reachability!.
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSArray *placemark = [results objectForKey:#"Placemark"];
NSArray *coordinates = [[placemark objectAtIndex:0] valueForKeyPath:#"Point.coordinates"];
double longitude = [[coordinates objectAtIndex:0] doubleValue];
double latitude = [[coordinates objectAtIndex:1] doubleValue];
[self zoomMapAndCenterAtLatitude:latitude andLongitude:longitude];}
I am currently using this code to get data from a URL:
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];
I was wondering how I could gather this data asynchronously so that my app does not freeze everytime I need to execute this. Thanks!
The simplest way is available in os5 like this:
NSString *stringfromFB;
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
stringfromFB = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]; // note the retain count here.
} else {
// handle error
}
}];
If you're stuck in os<5 for some reason, you'll need to start your connection with a delegate, and implement the delegate protocol as illustrated here (and many places elsewhere).
You can do it with GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url]
});
// Do not alloc init URL obj. for local use.
NSString *urlString = #"put your url string here";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above delegate methods are of NSURLConnectionDelegate, where you need to handle all things like response error etc.. It is by default provided so we can directly override it without
I have use once in my project It will work for async request but If you received number of images as well then also use IconDownloader or EGOImageView which implements the lazy loading of image and make much low chances of freezing of app.
if you don’t want to wait for a connection to complete loading a url, you can load it asynchronously using NSURLConnection.
[NSURLConnection connectionWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:yourUrlString]]
delegate:self];
Now that NSURLConnection is deprecated you need to use NSURLSession.
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == STATUS_OK) {
// use data
}
else {
NSLog(#"Network Session Error: %#", [networkError localizedFailureReason]);
}
}];
[task resume];
I want to do a simple google image search and return one image for whatever is string I'm searching for. image is null when I finish, what am I doing wrong? Code below:
-(void)getGoogleImage
{
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *newGoogle = [google stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",newGoogle];
NSURL * url = [NSURL URLWithString:fullGoogle];
NSURLRequest * request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Recieve Response");
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSLog(#"Did Recieve Data");
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
image = [[UIImage alloc]initWithData:responseData];
}
When i search for dog i get this in a web browser:
{"responseData": {"results":[{"GsearchResultClass":"GimageSearch","width":"220","height":"211","imageId":"ANd9GcTZKvO0mDGuDdifdhW3TEG8bmcPM23DMGEB4wevzBuIPp7HMMwQ3dTetVc","tbWidth":"107","tbHeight":"103","unescapedUrl":"http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%2B1.jpg/220px-Timba%2B1.jpg","url":"http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%252B1.jpg/220px-Timba%252B1.jpg","visibleUrl":"en.wikipedia.org","title":"\u003cb\u003eDog\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Dog - Wikipedia, the free encyclopedia","originalContextUrl":"http://en.wikipedia.org/wiki/Dog","content":"the appropriate-sized \u003cb\u003edog\u003c/b\u003e","contentNoFormatting":"the appropriate-sized dog","tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcTZKvO0mDGuDdifdhW3TEG8bmcPM23DMGEB4wevzBuIPp7HMMwQ3dTetVc"},{"GsearchResultClass":"GimageSearch","width":"170","height":"224","imageId":"ANd9GcTycy7IfwO9VLFIftSa7yNZj1b_BP583qUQ0UmSZnog_jdhdwvewcWvrw","tbWidth":"82","tbHeight":"108","unescapedUrl":"http://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Golden_retriever_eating_pigs_foot.jpg/170px-Golden_retriever_eating_pigs_foot.jpg","url":"http://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Golden_retriever_eating_pigs_foot.jpg/170px-Golden_retriever_eating_pigs_foot.jpg","visibleUrl":"en.wikipedia.org","title":"\u003cb\u003eDog\u003c/b\u003e - Wikipedia, the free encyclopedia","titleNoFormatting":"Dog - Wikipedia, the free encyclopedia","originalContextUrl":"http://en.wikipedia.org/wiki/Dog","content":"See also: \u003cb\u003eDog\u003c/b\u003e food","contentNoFormatting":"See also: Dog food","tbUrl":"http://t1.gstatic.com/images?q\u003dtbn:ANd9GcTycy7IfwO9VLFIftSa7yNZj1b_BP583qUQ0UmSZnog_jdhdwvewcWvrw"},{"GsearchResultClass":"GimageSearch","width":"334","height":"360","imageId":"ANd9GcTsX8rcRiPIMso7akKaQmVP4PzMwoAfbVnlc6KkPNG5jpU7wfyZNWy1oNs","tbWidth":"112","tbHeight":"121","unescapedUrl":"http://www.petscarecenter.com/wp-content/uploads/2011/05/dog.jpg","url":"http://www.petscarecenter.com/wp-content/uploads/2011/05/dog.jpg","visibleUrl":"www.petscarecenter.com","title":"Tips for \u003cb\u003eDog\u003c/b\u003e Care","titleNoFormatting":"Tips for Dog Care","originalContextUrl":"http://www.petscarecenter.com/dog-care/tips-for-dog-care.html","content":"Since \u003cb\u003edogs\u003c/b\u003e are known for the","contentNoFormatting":"Since dogs are known for the","tbUrl":"http://t0.gstatic.com/images?q\u003dtbn:ANd9GcTsX8rcRiPIMso7akKaQmVP4PzMwoAfbVnlc6KkPNG5jpU7wfyZNWy1oNs"},{"GsearchResultClass":"GimageSearch","width":"400","height":"366","imageId":"ANd9GcS6VxIzGltwNb2PWMGDfoBvvuof26Kn9i_BrXYRvgWqpnnT3UNfy5DYyC8","tbWidth":"124","tbHeight":"113","unescapedUrl":"http://static.ddmcdn.com/gif/dog-best-friend-1.jpg","url":"http://static.ddmcdn.com/gif/dog-best-friend-1.jpg","visibleUrl":"animals.howstuffworks.com","title":"Is a \u003cb\u003edog\u003c/b\u003e really a man\u0026#39;s best friend?: \u003cb\u003eDog\u003c/b\u003e Care: Animal Planet","titleNoFormatting":"Is a dog really a man\u0026#39;s best friend?: Dog Care: Animal Planet","originalContextUrl":"http://animals.howstuffworks.com/pets/dog-best-friend.htm","content":"\u003cb\u003eDog\u003c/b\u003e Image Gallery","contentNoFormatting":"Dog Image Gallery","tbUrl":"http://t3.gstatic.com/images?q\u003dtbn:ANd9GcS6VxIzGltwNb2PWMGDfoBvvuof26Kn9i_BrXYRvgWqpnnT3UNfy5DYyC8"}],"cursor":{"resultCount":"3,460,000,000","pages":[{"start":"0","label":1},{"start":"4","label":2},{"start":"8","label":3},{"start":"12","label":4},{"start":"16","label":5},{"start":"20","label":6},{"start":"24","label":7},{"start":"28","label":8}],"estimatedResultCount":"3460000000","currentPageIndex":0,"moreResultsUrl":"http://www.google.com/images?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003ddog","searchResultTime":"0.07"}}, "responseDetails": null, "responseStatus": 200}
instead of doing a manual url encoding of your url like you do:
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *newGoogle = [google stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",newGoogle];
NSURL * url = [NSURL URLWithString:fullGoogle];
NSURLRequest * request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Try the method:
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
which does a more accurate encoding of the url:
NSString *google = [NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults]objectForKey:#"string"]];
NSString *fullGoogle = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",google];
NSString * urlEncoded = [fullGoogle stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:urlEncoded];
NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Maybe this is your problem, hope it helps!
You need this in connectionDidFinish
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *test = [json objectForKey:#"responseData"];
NSDictionary *closer = [test objectForKey:#"results"];
NSArray *closest = [closer valueForKey:#"url"];
I am trying to use initWithContentsOfURL:encoding:error: like this :
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
I get a empty my_string variable.
I tried the initWithContentsOfURL: method (which is deprecated in iOS 2.0) and I get the content of my page. But I still need to specify a encoding language.
What's wrong ?
Thanks :)
the encoding of your file is probably not UTF8.
If you don't know the encoding of your file, you could try this method:
- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
you have to pass a pointer to a NSStringEncoding, like you did with error.:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSStringEncoding encoding;
//NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
// encoding:NSUTF8StringEncoding
// error:&error];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
after this your encoding is present in the encoding variable. If you are not interested in the used encoding, I guess you could pass NULL as pointer as well.
Why not use a request and connection to get the info back in an NSData object? Something like this:
NSURL *url = [[NSURL alloc] initWithString:#"http://my_url.com/my_file.xml"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn){
// Data Received
responseData = [[NSMutableData alloc] init];
}
and then in your connection:didRecieveData delegate method, put something like this
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
and then once the connection is finished loading convert the data to a string:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}
Not the most straightforward method, but that should get you your XML string. Also if you need to parse the XML once you get it back, you can directly pass the responseData to an NSXMLParser without any conversion. :)
You can modify your webpage by adding header('Content-Type: text/html; charset=UTF-8'); to the top of the code and saving the document as a UTF-8 formated file. It helped me as I had the same problem.