Someone I work with created a website that he wants to use to provide a service. They run a php script when the user taps Login that checks username/password/etc
Now I want to write an app that would allow logging in and also retrieving data, as one would on the website. How can I pass the login info from the iOS device to that PHP script that is run on the website? And after I'm logged in, how can I check and retrieve the data?
Do I need to ask him for an API?
responseData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.yourwebsite.com/login.php"]];
NSString *params = [[NSString alloc] initWithFormat:#"user=myuser&pass=mypass"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
Related
I am unable to upload an image from my device's Photos in a background session. When I call [session uploadTaskWithRequest:req fromFile:nsurl] the system immediately complains by sending
Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/103APPLE/IMG_3984.JPG, errno = 1
to the console. (A similar Stack Overflow issue is here)
However, if I create my NSURLSessionConfiguration with [NSURLSessionConfiguration defaultSessionConfiguration] (instead of [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:id], which I need) and if I construct an NSData object out of the NSURL and upload that instead of uploading straight from a file (which is required by a background session) then the upload succeeds. Btw I'm uploading files into our Rackspace Cloud account, and am able to do this successfully with a simple Postman PUT.
The problem occurs in my uploadObject method, which looks like:
-(void) uploadObject:(NSURL*)urlToBeUploadedIn
{
NSDictionary *headers = #{ #"x-auth-token": state.tokenID,
#"content-type": #"image/jpeg",
#"cache-control": #"no-cache" };
// create destination url for Rackspace cloud upload
NSString *sURL = [NSString stringWithFormat:#"%#/testing_folder/%#.jpg", state.publicURL, [state generateImageName]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"PUT"];
[request setAllHTTPHeaderFields:headers];
self.sessionIdentifier = [NSString stringWithFormat:#"my-background-session"];
// NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; // when I use this instead of the line below the sandbox error goes away
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sessionIdentifier];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:urlToBeUploadedIn];
[uploadTask resume];
}
My call that invokes uploadObject: looks like:
PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:state.arrImagesToBeUploaded options:nil];
PHAsset *phAsset = [fetchResult objectAtIndex:0]; // yes the 0th item in array is guaranteed to exist, above.
[phAsset requestContentEditingInputWithOptions:nil
completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {
NSURL *imageURL = contentEditingInput.fullSizeImageURL;
[self uploadObject:imageURL];
}];
Btw I first validate the NSURL I send to uploadObject: with a call to fileExistsAtPath: so I know my reference to the file is good. Finally, my delegate calls
(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)dataIn
(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error does get invoked, although the data
do get called by the server (although the response won't parse) so, I am getting something back from the server which never correctly receives the image.
A solution is to first copy the image to be uploaded into the app's sandbox. I used:
NSError *err;
BOOL bVal = [myNSDataOb writeToURL:myDestinationURL options:0 error:&err];
and copied into my app's 'Documents' directory, but one might also use:
NSError *err;
BOOL bVal = [[NSFileManager defaultManager] copyItemAtURL:myImageURL toURL:myDestinationURL error:&err];
I have set up a ASP.NET Web service that I have tested on the server through the auto-generated service webpage.
But I can't post data to it correctly by an iOS app. **I'm getting no errors but its also not ever firing the method of the web service.
Please help..
NSURL *siteURL = [NSURL URLWithString:#"http://server/.../IOSDataWebService/Service1.asmx?op=testMethod"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:siteURL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSString *postString = #"fieldToAdd=TestString";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:postString forHTTPHeaderField:#"Content-Length"];
[NSURLConnection connectionWithRequest:request delegate:self];
Try setting postString.length, instead of postString itself, as the value of the Content-Length header.
Oh, wait, you can't set just a bare integer there. Let's try wrapping it as a NSNumber instead with #(postString.length).
I am trying to use ObjectiveFlickr with the following sample API call but my code ends with an EXC_BAD_ACCESS. I made sure that my key and shared secret exist in flickr:
OFFlickrAPIContext *context = [[OFFlickrAPIContext alloc] initWithAPIKey:apiKey sharedSecret:sharedSecret];
OFFlickrAPIRequest *request = [[OFFlickrAPIRequest alloc] initWithAPIContext:context];
[request setDelegate:self];
[request callAPIMethodWithGET:#"flickr.photos.getRecent" arguments:[NSDictionary dictionaryWithObjectsAndKeys:#"1", #"per_page", nil]];
I had the same error, look here: ObjectiveFlickr & Xcode 4.5.2
Declare the context and request variables as properties instead, and it'll get rid of the EXC_BAD_ACCESS
I am trying to login automatically into an ASP.NET website using NSMutableURLRequest. I am sending through all the post parameters I can think of, and it works well with other websites. (eg. Wordpress based). But I am unable to get it to work for ASP.net websites. Can someone please explain to me how I could go about this issue?
NSString *post = #"__LASTFOCUS=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNjM4NDU2MzY5ZGT%2F7rz73weImm5JbYQQ4q2lRY3HUw%3D%3D&__EVENTVALIDATION=%2FwEWBQK9gI6LAwKY4eTfDQKmw8%2B%2FAQLerrfAAwKQxuCGAT0xfZqPEPwFCfa5fbrvTZXDSnbY&ctl00%24SideBarContent%24UserName=demo&ctl00%24SideBarContent%24Password=demo&ctl00%24SideBarContent%24LoginButton=Login&ctl00%24SideBarContent%24UserTimeZoneCrawler%24offset=02%3A00%2C0";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *postRequest = [[NSMutableURLRequest alloc] init];
[postRequest setURL:[NSURL URLWithString:#"http://asp.net/website/logon.aspx"]];
[postRequest setHTTPMethod:#"POST"];
[postRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[postRequest setHTTPBody:postData];
[postRequest setValue:#"loginCookie=UserName=demo; SessionContext=ydnwyyz5n50mt2zjn3yiarq0" forHTTPHeaderField:#"Cookie"];
Regards,
EZFrag
You might have to pass your username/password in with your URL.
[postRequest setURl:[NSURL URLWithString:#"http://<username>:<password>#asp.net/website/login.aspx"]];
I ended up with letting the users enter their usernames and passwords manually every time. I am still open to any suggestions though.
Regards,
EZFrag
I am developing an app with phonegap, however I am trying to generate Push Notification call through plugin with NSUrlconnection.
Notification does work with following command
curl -X POST -u ":" -H "Content-Type: application/json" --data '{"device_tokens": [""], "aps": {"alert": "Vikrant say Hello!","badge": "5"}}' https://go.urbanairship.com/api/push/
NOW I AM TRYING SAME WITH BELOW CODE
NSString *URL = #"https://go.urbanairship.com/api/push/";
NSMutableURLRequest *req = [[[NSMutableURLRequest alloc] init] autorelease];
[req setURL:[NSURL URLWithString:URL]];
[req setHTTPMethod:#"POST"];
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"application/json; boundary=%#",boundary];
[req addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"{\"device_tokens\": [\"<devce token>\"], \"aps\": {\"alert\": \"Vikrant say Hello!\",\"badge\": \"5\"}}"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:body];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
finished = NO;
finishedWithError = NO;
if(xmlData == nil)
[xmlData release];
if(conn)
{
xmlData = [[NSMutableData alloc] retain];
while(!finished)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
So, its a HTTPS url with server authentication. So i have written the delegates.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge *)challenge
{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
NSLog(#"Trust Challenge Requested!");
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
else if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic])
{
NSLog(#"HTTP Auth Challenge Requested!");
NSURLCredential *credential = [[NSURLCredential alloc] initWithUser:#"<apikey>" password:#"<master key>" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
[credential release];
}
}
The problem is, connection is not accepting the username and password. because prints below output
2000-01-01 11:07:09.-540 WIPT[500:307] From APN
[Switching to thread 13059]
2000-01-01 11:07:13.-986 WIPT[500:307] Trust Challenge Requested!
2000-01-01 11:07:14.-82 WIPT[500:307] didReceiveResponse
2000-01-01 11:07:14.-25 WIPT[500:307] connection
2000-01-01 11:07:14.-05 WIPT[500:307] connectionDidFinishLoading
2000-01-01 11:07:15.-958 WIPT[500:307] APN response data Authorization Required
It means it executes the URL but dose not send Username and password. Does anybody know the solution
The push API calls are normally authenticated with the master secret as the password, not the application secret. Consider the application secret to be a restricted access code that can be safely embedded in the app; you'd never embed the master secret inside your application.
However, to make some subset of push calls available without the master secret, you can enable the allow push from device flag on the Urban Airship application. This lets you make push calls directly to a device token with the application secret. It will not allow you to make pushes to aliases, tags, or do full broadcasts, as these can be guessed or can cost you lots of trouble.
Adam
Urban Airship
Replace NSURLAuthenticationMethodServerTrust with NSURLAuthenticationMethodHTTPBasic in canAuthenticateAgainstProtectionSpace delegate.
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic];
}