My program register users through URL-requests, but before registration there is existence userlogin or his e-mail checking in remote database. If this data not exist program should add user data in database or (if user or e-mail exist) program should return error.
I wrote this code:
- (IBAction)buttonRegister:(id)sender {
NSString *getDataURL = [NSString stringWithFormat:#"https://*********/********.php?chklogin=%#&chkemail=%#",login.text,email.text];
NSURL *url = [NSURL URLWithString:getDataURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection)
urlDataCheckUser = [NSMutableData data];
else NSLog(#"Connection failed!");
}
- (void) msgtitle: (NSString*) title msgtext: (NSString*) msg
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[urlDataCheckUser appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *strResult = [[NSString alloc] initWithData:urlDataCheckUser encoding:NSUTF8StringEncoding];
if ([strResult isEqualToString:#"1"])
{
[self msgtitle:#"Error" msgtext:#"E-mail or Login already use!"];
}
if ([strResult isEqualToString:#""])
{
NSString *getDataURL = [NSString stringWithFormat:#"https://**********/**********.php?reglogin=%#®email=%#®pass=%#",login.text,email.text,password.text];
NSURL *url = [NSURL URLWithString:getDataURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url];
NSURLConnection *conn =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
theRequest = nil;
if (conn)
{
[self msgtitle:#"Success!" msgtext:#"Please login"];
}
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"loginView"];
[self presentViewController:vc animated:YES completion:nil];
}
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
It is work, but i get message about successful registration more then once.
What is wrong?
Related
I am loading a url which has authentication So I used the following code
BOOL _authed = NO;
NSURLAuthenticationChallenge *mChallenge;
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSLog(#"Did start loading: %# auth:%d", [[request URL] absoluteString], _authed);
if (!_authed) {
_authed = NO;
[NSURLConnection alloc]initWithRequest:request delegate:self];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(#"got auth challange");
_authed = YES;
mChallenge = challenge;
UIAlertView *prompt = [[UIAlertView alloc]initWithTitle:nil message:#"Authentication Required" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Login", nil];
prompt.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[prompt show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 1){
UITextField *usernameField = [alertView textFieldAtIndex:0];
UITextField *passwordField = [alertView textFieldAtIndex:1];
NSString *userName = usernameField.text;
NSString *password = passwordField.text;
NSLog(#"%#, %#",userName,password);
[[mChallenge sender] useCredential:[NSURLCredential credentialWithUser:userName password:password persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:mChallenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
NSLog(#"response %#",response);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://mysharepointurl.aspx"]];
[self.webView loadRequest:request];
}
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection;
{
return NO;
}
this works fine if I try correct password first time.
But when I try with wrong credential first time, the prompt comes again and then I try with correct credential, then web view will not be loaded
any advice on this
I am using the Yelp Search API to basically just get a list of businesses for a search query.
It is pretty much a NSURLConnection is OAuth, but here is the code to initialize the request:
NSURL *URL = [NSURL URLWithString:appDelegate.yelpAdvancedURLString];
OAConsumer *consumer = [[OAConsumer alloc] initWithKey:#"this-is-my-key" secret:#"this-is-my-secret"];
OAToken *token = [[OAToken alloc] initWithKey:#"this-is-my-key" secret:#"this-is-my-secret"];
id<OASignatureProviding, NSObject> provider = [[OAHMAC_SHA1SignatureProvider alloc] init];
NSString *realm = nil;
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:URL
consumer:consumer
token:token
realm:realm
signatureProvider:provider];
[request prepare];
responseData = [[NSMutableData alloc] init];
yelpConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Then here:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#, %#", [error localizedDescription], [error localizedFailureReason]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Oops." message: #"Something screwed up. Please search again." delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.yelpConnection) {
[self setYelpString];
}
}
When I run this on iPhone, everything is working fine. However, when I run on iPad, the connection gets timed out. The following is from this line
NSLog(#"Error: %#, %#", [error localizedDescription], [error localizedFailureReason]);
Error: The request timed out., (null)
Also if I use a synchronous request, it seems to work using this:
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary* JSON = [NSJSONSerialization
JSONObjectWithData:result
options:kNilOptions
error:&error];
However, I want to avoid using synchronous as it freezes the app.
Is this Yelp API specific? Or am I just doing something wrong? Thanks in advance, I would appreciate any help.
If it helps, it times out approximately 10 seconds after sending the request.
create this type of NSMutableURLRequest :
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:240.0];
I think the best approach is to change the init method in http://oauth.googlecode.com from
- (id)initWithURL:(NSURL *)aUrl
consumer:(OAConsumer *)aConsumer
token:(OAToken *)aToken
realm:(NSString *)aRealm
signatureProvider:(id<OASignatureProviding, NSObject>)aProvider
{
if (self = [super initWithURL:aUrl
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10.0])
{
...
}
}
to
- (id)initWithURL:(NSURL *)aUrl
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
timeoutInterval:(NSTimeInterval)timeoutInterval
consumer:(OAConsumer *)aConsumer
token:(OAToken *)aToken
realm:(NSString *)aRealm
signatureProvider:(id<OASignatureProviding, NSObject>)aProvider
{
if (self = [super initWithURL:aUrl
cachePolicy:cachePolicy
timeoutInterval:timeoutInterval])
{
...
}
and then check again, whether the timeout value which you specify will be honored by the connection.
I am beginner in IOS programming. My question is my app fetching data from JSON in my web server, when starting the apps, it is slightly lag and delay due to the fetching process, so i would like to show activity indicator when i connecting to JSON data. How can i do that?
My JSON coding:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *urlAddress = [NSURL URLWithString:#"http://emercallsys.webege.com/RedBoxApp/getEvents.php"];
NSStringEncoding *encoding = NULL;
NSError *error;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:&error];
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[jsonreturn release];
}
use the following code
//add a UIActivityIndicatorView to your nib file and add an outlet to it
[indicator startAnimating];
indicator.hidesWhenStopped = YES;
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
//Load the json on another thread
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:urlAddress usedEncoding:encoding error:NULL];
[jsonreturn release];
//When json is loaded stop the indicator
[indicator performSelectorOnMainThread:#selector(stopAnimating) withObject:nil waitUntilDone:YES];
});
You can use something like below code:
- (void)fetchData
{
[activityIndicator startAnimating];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *theRequest = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(theConnection) {
}
else {
NSLog(#"The Connection is NULL");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction %#",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:#"Information !" message:#"Internet / Service Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//NSLog(#"Received data :%#",theXML);
//[theXML release];
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary: webData error:&error];
if (dict) {
eventsDetail = [[dict objectForKey:#"eventsDetail"] retain];
}
[activityIndicator stopAnimating];
}
i am using NSURLConnection to download mp3 files from server, my code is
- (IBAction)download:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSLog(#"%#", url);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"myFile.mp3"];
[receivedData writeToFile:documentsDirectoryPath atomically:YES];
[connection release];
}
when i click download button, the activity indicator start animating and stops after some time (i think it is downloading). but after that i can't find the downloaded file on my iPhone disk. actually where those files stored after downloading.
i have edited my info.plist to support iTunes file sharing.
is their any mistake with this code? or why can't i see the downloaded files?
My Created one class for downloading ringtones, See first RingtoneDwonloader.h file
import
#protocol RingtoneDownloaderDelegate
-(void)downloadingCompleted;
#end
#interface RingtoneDownloader : NSObject
{
NSMutableData *receivedData;
NSDate *connectionTime;
NSMutableString *diskPath;
id<RingtoneDownloaderDelegate>delegate;
}
#property(nonatomic, retain) iddelegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString;
-(void)cancelDownloading;
#end
Now my RingtoneDownloader.m file,
import "RingtoneDownloader.h"
import "AppDelegate.h"
#interface RingtoneDownloader(){
AppDelegate *_appDelegate;
NSURLConnection *theConnection;
}
#end
#implementation RingtoneDownloader
#synthesize delegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString{
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
[receivedData setLength:0];
// long responseLength = [response expectedContentLength];
// NSLog(#"%ld", responseLength);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[theConnection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
UIAlertView *alt = [[UIAlertView alloc] initWithTitle:#"" message:[NSString stringWithFormat:#"%#", [error localizedDescription]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
// inform the user
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *soundFileName = _appDelegate.ringtoneURL;
NSString *soundFileextension = [soundFileName substringFromIndex:([soundFileName length]-3)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", _appDelegate.ringtoneText, soundFileextension]];
NSData *imageData = (NSData *)receivedData;
NSError *err = nil;
BOOL isWriten = [imageData writeToFile:filePath options:NSDataWritingAtomic error:&err];
if(!isWriten){
NSLog(#"Ringtone not saved %#", [err localizedDescription]);
}
[theConnection release];
[receivedData release];
[delegate downloadingCompleted];
}
-(void)cancelDownloading{
[theConnection cancel];
[theConnection release];
[delegate downloadingCompleted];
}
Now u have to just created and instance of this class and set the delegate that i m create. That delegate give u information regarding your ringtone file is successfully downloaded or not.
Use iTunes file sharing in your app and copy the ringtone file to the app's documents directory.
Set "Application supports iTunes file sharing" to YES in your info.plist
The user can now access the ringtone via itunes and add it to their devices ringtones.
I want to create connection from my iphone to my website where I will be retrieving data that needs to be parsed. I am not having any luck so far and am kind of confused in regard to the following delegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
Are these methods called upon there own from my code or do I manually need to call them? Do I need to declare a delegate anywhere in my .h file?
This is what I have been doing but have had no luck. If anyone can explain it would be appreciated. It says my connection is successful made but the NSLog comes up in the console for didFailWithError.
Thanks
-(void) data: (id) sender
{
NSString *stringToBeSent;
NSURL *siteWithNumbers;
NSString *translation;
NSError *error;
NSString *boo;
sender= [sender lowercaseString];
sender= [sender stringByReplacingOccurrencesOfString:#"," withString:#""];
receivedData= [[NSMutableData alloc] init]; //declared in .h file as NSMutableData
stringToBeSent= [[NSString alloc]
initWithFormat:#"http://xxxx/sql.php? data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:stringToBeSent]];
NSURLConnection *conn= [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
//[self createConnectionWithPath:stringToBeSent];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
NSLog(#"here now1");
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[conn release];
conn = nil;
}
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
{
NSLog(#"fail");
}
//in .h file
#interface yourViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *responseData;
}
// in .m file
-(void) data: (id) sender
{
NSString *strWithURL = [NSString stringWithFormat:#"%#%#",TownsServiceURL,state];
strWithURL = [strWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strConfirmChallenge=%#",strWithURL);
NSURL *myURL = [NSURL URLWithString:strWithURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
UIAlertView *ConnectionFailed = [[UIAlertView alloc]
initWithTitle:#"Connection Failed"
message: [NSString stringWithFormat:#"%#", [error localizedDescription]]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[ConnectionFailed show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}