How to upload images in a scrollview onto a web server? - ios

I have an iOS app that has a series of images in a scrollview (camera pictures). I want to be able to post these on to a url individually or collectively as a group.
Can someone point me to an example or some sample code that would get me started?
Much appreciated

in that case if you if you set up your server (how do this i don`t now, because i used quickblox - ready-made solution) try send GET-request to the server. You can try this like this:
(source - How to send a Get request in iOS? )
NSString *getString = [NSString stringWithFormat:#"parameter=%#",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:#"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https:yoururl"]];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, #"Failure to create URL connection.");
// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
For more advanced preferences I would advise you try learn http://allseeing-i.com/ASIHTTPRequest/

For this you can create file server or use other maded. Look this: http://quickblox.com/ - they has blobs and ios api for their server, so download|upload files simple implemented in code.
First, you need register your account and then register your app.( https://admin.quickblox.com/signin ) (it's not difficult, few minuts)
Then, using instructions from site added Quickblox auth to your app and then use QBBlobs for dowload photo. Good luck!

Related

POST JSON data to specific object iOS

I have read several posts on Stack about how to POST data using both XML and JSON however nothing is standing out to me about how to update a selected object.
I am pulling down data from my boss' job tracking API fine, all things are accounted for. However I want to update individual selected object's variables.
Example:
If I have a recipe site API and I am pulling down 100 recipes and displaying the titles in a table. I select a row and it displays a new screen which shows all the details about the recipe with textfields for updating content and a button that will save to the website. How do I update an ingredient on the selected recipe so that it is represented on the website?
Bare in mind I am using my business' API and not Parse.com or another server based database.
I would prefer to use JSON however if there are better solutions using XML I am fine with that.
New Thought
Do I have to replace the entire object when updating?
More Info
Due to using an API, I do not have links directly to a specific object. I get given the block (100 recipes), have to iterate through the block to save each object as NSObject and then sort the newly stored NSObjects how I like to. When I select a row, I am selecting an object that has been sorted and displaying that objects contents. I don't know if this information is helpful or not.
The reason for this extra information is:
When trying to update the Object through the API, how do I know I am updating that specific object and not the entire list of objects?
I think you want to POST data onto the existing fields:
You can try this to POST the data:
NSString *post = [NSString stringWithFormat:#"text_field1=%#",text_field.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://your api to recieve the data into the fields"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
}
I think you can use Mantle on GitHub.
https://github.com/Mantle/Mantle

DownLoad Data from server with "Pause" and "Resume" functionality

I want to download a file with pause/resume functionality. I read apple documents, there I got NSUrldownload which supports the same but it is not available for iOS. I was trying with NSUrlconnection, but not working. I don't want to use any third party libraries, I want to implement it by myself, below is the code snippet which I tried.
NSString *fileName = [NSString stringWithFormat:#"~%#",[[url componentsSeparatedByString:#"/"] lastObject]];
int dataLength = [[self checkDocDirectoryforFileName:fileName] length];
//dataLength = 0;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"audio/mpeg" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"bytes" forHTTPHeaderField:#"Accept-Ranges"];
[request setValue:#"Keep-Alive" forHTTPHeaderField:#"Connection"];
[request setValue:[NSString stringWithFormat:#"%d",dataLength] forHTTPHeaderField:#"Content-Length"];
NSLog(#"Request header %#", [request allHTTPHeaderFields]);
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
Please check it out this:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLDownload.html#//apple_ref/doc/uid/20001839-SW2
Hope, May it will help you,
:)
iOS 7.0 and above
NSURLSession especially NSURLSessionDownloadTask provides this functionality.
The NSURLSession API provides status and progress properties, in
addition to delivering this information to delegates. It supports
canceling, restarting or resuming, and suspending tasks, and it
provides the ability to resume suspended, canceled, or failed
downloads where they left off.
Take a look to the docs.
iOS 5.0 and above
I would use AFDownloadRequestOperation for this. Take a look at this thread.
AFDownloadRequestOperation has
additional support to resume a partial download, uses a temporary
directory and has a special block that helps with calculating the
correct download progress.

Run the ASIHTTPRequest in background when View reloads

I am developing a application which uses ASIHTTPRequest to download the content from server. When downloading if I move from Portrait to Landscape mode the downloads process is going to stop. I need the download process still to be continued.
I have searched for the solution in stackoverflow but no useful.
How can I solve this problem...
This is the piece of code i am using to download.
NSURL *downloadURL = [publisher contentURLForIssueWithName:issueTitle];
if (!networkQueue) {
networkQueue = [[ASINetworkQueue alloc] init];
}
if(!downloadURL) return;
[self performSelectorInBackground:#selector(read) withObject:nil];
request = [ASIHTTPRequest requestWithURL:downloadURL];
[request setDelegate:self];
[request setDownloadProgressDelegate:progressView];
[request setShowAccurateProgress:YES];
request.shouldContinueWhenAppEntersBackground=YES;
request.allowResumeForFileDownloads=YES;
[request startAsynchronous];
Any help to be appreciated..

Fetching an access token for youtube api iOS "Error" : "invalid_request"

I'm trying to get an access token for a youtube app for iOS. Here's the relevant code I have been using from my viewDidLoad method:
mAuth = [[GTMOAuth2Authentication alloc]init];
[mAuth setClientID:#"<MY CLIENT ID>"];
[mAuth setClientSecret:#"<MY CLIENT SECRET>"];
[mAuth setRedirectURI:#"urn:ietf:wg:oauth:2.0:oob"];
[mAuth setScope:#"https://gdata.youtube.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?client_id=%#&redirect_uri=%#&scope=%#&response_type=code&access_type=offline", mAuth.clientID, mAuth.redirectURI, mAuth.scope]]]];
After this is called, the user has to grant access to their account, then I retrieve the auth code from the resulting page in the following code:
NSString *string = [self.web stringByEvaluatingJavaScriptFromString:#"document.title"];
if([string rangeOfString:#"Success"].location != NSNotFound){
NSLog(#"This is the code page");
NSString *importantCode = [[string componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"%#", importantCode);
if([self.defaults objectForKey:#"super important code"] == nil){
[self.defaults setObject:importantCode forKey:#"super important code"];
[self.defaults synchronize];
NSString *post = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=code", [self.defaults objectForKey:#"super important code"], mAuth.clientID, mAuth.clientSecret, mAuth.redirectURI];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"]]];
[request setHTTPMethod:#"POST"]; [request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[self.web loadRequest:request];
}
[timer invalidate];
}
After that, I should be given the access token in response to my POST request, but instead I get a page that simply says:
{
"error" : "invalid_request"
}
Does anyone (see where I went wrong)/(know how to retrieve the access token)?
I’d be interested in knowing what the HTTP status code is... I suspect ”invalid_request” means 400, which almost always means there’s some irritating stupid little error in the way you composed your authent URI. I don’t know enough iOS/ObcJ to tell if you’ve properly URLescaped any funny characters in any of the parameter values, but it’s worth checking. Or a typo in one of the values, or an extra newline creeping in or something?
It was as simple as this, I had set the grant_type parameter to 'code' when it should have been 'authorisation_code' if you are reading this and you are using the youtube api, don't make the same mistake. If you're reading this and you're sending a POST request in general, this error "invalid_request" means that either you skipped one of the parameters you should have added, or you added it incorrectly.

Logging in from settings username and password preferences

I have an app that uses webView. In the home screen of a website I want to login using username and password entered by the user in the app's settings option. Currently I have this code which I saw in solution to a similar question asked on this forum. But it isn't working (neither it did for the other guy).
-(IBAction)cachepressed:(id)sender{
NSString *baseurl=[[NSUserDefaults standardUserDefaults] stringForKey:#"url_preference"];
NSString *username= [[NSUserDefaults standardUserDefaults] stringForKey:#"name_preference"];
NSString *password= [[NSUserDefaults standardUserDefaults] stringForKey:#"pswrd_preference"];
NSString* content = [NSString stringWithFormat:#"username=%#&password=%#", username, password];
NSData *data=[content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%d",[data length]];
NSString *loginpage= [baseurl stringByAppendingString:#"/index.php?title=Special:UserLogin"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:loginpage]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
NSError *error=nil;
NSURLResponse *response=nil;
NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *HTMLString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
[webView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:loginpage]];
}
I am not too sure about the two lines of code starting with [request setValue...]. Can somebody suggest a solution to this? It would be a great help. Thanks in anticipation.
This depends a lot on how the authentication is done on the website.
Based on what I can figure from your question, the code you posted sends values for the fields named "username" and "password" to the index.php?title=Special:UserLogin page using POST.
You need to make sure that everything is set accordingly.
1. Are your fields name the same on the website?
Maybe the login form uses different field names, not username and password. Check the source code and see if the input names are indeed "username" and "password"
2. Does your host allow posting data from a different source?
I used to set mine so no POST request would work if they didn't originate from my server, so POSTing data from an iPad would not have functioned.
Is this the case for you too?
3. The login process is really done by posting data to that page?
Maybe on the website the authentication is done using AJAX on a different php page and then you get redirected to index.php?title=Special:UserLogin, I've seen such cases in the past.
Bottom line is that you need to know exactly how the login is done on the website before doing it inside a webview. Correct me if I'm wrong, but based on your post it doesn't seem to be the case here

Resources