How to send HTTP POST request to PHP service with Objective-C - objective-c

Im trying to post to php and get the response. The php file has an echo "hello" which should just print hello. I'm trying to test to see if posting is working but in my error log the NSlog doesn't display anything:
#interface ViewController ()
#end
#implementation ViewController
#synthesize email, password,receivedData;
-(IBAction)Login:(id)sender{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"%#", email];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//initialize convert the received data to string with UTF8 encoding
NSString *htmlSTR = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"%#" , htmlSTR);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"%#" , error);
}

Since you did not mention about what kind of body type you want to use this example shows you how to post multipart/form-data request.
-(NSString *)generateRandomBoundryString {
CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef UUIDString = CFUUIDCreateString(kCFAllocatorDefault,UUID);
NSString *aNSString = (__bridge NSString *)UUIDString;
CFRelease(UUID);
CFRelease(UUIDString);
return aNSString;
}
-(IBAction)Login:(id)sender {
NSString *bndry = [self generateRandomBoundryString];
NSString *contentType = [[NSString alloc] initWithString:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", bndry]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.php"]];
[request setHTTPMethod:#"POST"];
[request setValue: contentType forHTTPHeaderField:#"Content-Type"];
//form-data block
NSMutableData *requestBody = [NSMutableData data];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"name", #"John"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"password", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:requestBody];
//form-data block
// NSURLConnection Asynchronous Block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rspreportStatus, NSData *datareportStatus, NSError *e)
{
if (e == nil)
{
// If all ok you can processes response data here.
}
else {
NSLog(#"%#", e.localizedDescription);
}
}];
}
If body is application/x-www-form-urlencoded you should change Content-Type value like this.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
and replace //form-data block block with this.
[requestBody appendData:[[NSString stringWithFormat:#"name=%#&password=%#", #"John", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
#"John" and #"myPassword" has to be URL encoded.

Related

NSURLSessionDataTask gives me incorrect token in a Login

I'm updating an iOS app in objective c, and i have the warning sendSynchronousRequest(_:returningResponse:) was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]
So I changed my code from:
-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters{
NSString *reponseStr;
NSMutableData *postbody = [NSMutableData data];
Setting *session =[Setting getSessionDataInstance];
NSString *todayDate=[Utils Datefromstring:[NSDate date] byFormatter:#"HH:mm:ss"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/services/?&time=%#", appDelegate.mainUrlString,todayDate]];
NSMutableURLRequest *request=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:600.0];
if([method isEqualToString:#"userLogin"])
{
[postbody appendData:[[NSString stringWithFormat:#"&param=login"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&username=%#",[parameters objectForKey:#"userName"]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&password=%#",[parameters objectForKey:#"password"]] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&apnstoken=123456789"] dataUsingEncoding:NSUTF8StringEncoding]];
}
if([method isEqualToString:#"userLogout"])
{
[postbody appendData:[[NSString stringWithFormat:#"&param=logOut"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"&user_id=%#",session.userId] dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:[NSString stringWithFormat:#"%#",session.sessionToken ] forHTTPHeaderField:#"token"];
}
NSString * dataLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postbody length]];
[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[ request setHTTPMethod: #"POST" ];
[ request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[ request setHTTPBody: postbody ];
NSLog(#"request===%#",[request allHTTPHeaderFields]);
NSLog(#"URL=====%#",[request URL]);
NSLog(#"request===%#",request);
NSError *theError = nil;
NSURLResponse *urlResponse = nil;
if ([self checkInternet])
{
//THE PART OF THE WARNING ------
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&theError];
if(theError==nil){
reponseStr= [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
NSLog(#"ServerResponse===%#",reponseStr);
}
else{
NSLog(#"sendSynchronousRequest error = %#",theError.localizedDescription);
}
}
else{
reponseStr=#"Network not Available.";
}
return reponseStr;
}
- (BOOL) connectedToNetwork
{
Reachability *r = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [r currentReachabilityStatus];
BOOL internet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
internet = NO;
} else {
internet = YES;
}
return internet;
}
-(BOOL) checkInternet
{
//Make sure we have internet connectivity
if([self connectedToNetwork] != YES)
{
return NO;
}
else {
return YES;
}
}
NEW CODE --just adding the parts that modified
-(NSString*)getServerResponseByMethod:(NSString*)method clientId:(NSString*)clientId deviceid:(NSString*)deviceid token:(NSString*)token parameters:(NSDictionary*)parameters
{
__block NSString *reponseStr;
.......
NSString * dataLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postbody length]];
[request addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod: #"POST" ];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody: postbody ];
NSLog(#"request===%#",[request allHTTPHeaderFields]);
NSLog(#"URL=====%#",[request URL]);
NSLog(#"request===%#",request);
//NSError *theError = nil;
//NSURLResponse *urlResponse = nil;
if ([self checkInternet])
{
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if(error==nil)
{
reponseStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"ServerResponse===%#",reponseStr);
}
else
{
NSLog(#"sendSynchronousRequest error = %#",error.localizedDescription);
}
}];
[task resume];
}
else
{
reponseStr=#"Network not Available.";
}
return reponseStr;
}
With this new code, every time I log in displays the message that my username or password is incorrect but with the deprecated method everything works fine.
Any help will be awesome! I've been struggling with this like 3 hours :(
Thanks!
It seems you mixed up between POST or GET in your post body.
Any URL with format
http://abcde.com/what.php?a=1&b=2
is a GET method.
And what you specify is POST method. So make clear about that first.
Secondly, if you are using POST, then the data to post should be formatted
properly (example: https://stackoverflow.com/a/19101084/501439). All the "&"
in your postbody is causing the problem I am sure.

Post data on web server with web service

Hello I am tying to save data on web server with a web service implemented in PHP.
I am trying below code to do it. I am getting response from server but the data is not getting saved to server. I have wasted 5-6 hours of the day in googling and trying code given on net. But nothing seems to work :(
NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtTreasureName.text, #"name",
txtDescription.text, #"description",
txtMaterials.text, #"materials",
#"77.3833", #"longitude",
#"29.0167", #"latitude",
categoryIdStr, #"categoryId",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:treasureInfo
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
DLog(#"Got an error: %#", error);
} else {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlString = #"http://www.myurl.php";
NSURL *url = [NSURL URLWithString:urlString];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json"
forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json"
forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d",
[jsonData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:jsonData];
DLog(#"%#", request);
[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
// Print json
DLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *error) {
if ([data length] &&
error == nil) {
DLog(#"%#", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
if ([self shouldDismiss]) {
[self dismissViewControllerAnimated:YES
completion:nil];
}
}
}];
}
Set Request URL in the function,
You have alread y created data Dictionary
NSDictionary *someInfo = [NSDictionary dictionaryWithObjectsAndKeys:
txtTreasureName.text, #"name",
txtDescription.text, #"description",
txtMaterials.text, #"materials",
#"77.3833", #"longitude",
#"29.0167", #"latitude",
categoryIdStr, #"categoryId",
nil];
Add this function to your implementation file and invoke it, rest will be dont by this function
[self postWith:someInfo];
Add this
- (void)postWith:(NSDictionary *)post_vars
{
#warning Add your Webservice URL here
NSString *urlString = [NSString stringWithFormat:#"YourHostString"];
NSURL *url = [NSURL URLWithString:urlString];
NSString *boundary = #"----1010101010";
// define content type and add Body Boundry
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSEnumerator *enumerator = [post_vars keyEnumerator];
NSString *key;
NSString *value;
NSString *content_disposition;
while ((key = (NSString *)[enumerator nextObject])) {
value = (NSString *)[post_vars objectForKey:key];
content_disposition = [NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key];
[body appendData:[content_disposition dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close the request body with Boundry
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request addValue:[NSString stringWithFormat:#"%d", body.length] forHTTPHeaderField: #"Content-Length"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
}

Uploading Image via POST in Objective C

I'm currently working on uploading an image to a server via HTTP Post and can't seem to figure out a way to build the url that calls the service. The user selects an image from the library or camera and then calls a json service that performs the insert statement.
The service is expecting the following uritemplate:
#"%#/DataTransfer/SetUserProfileImage?EMP_ID=%#&image=%#&imageName=%#"
It is expecting that the image data is converted somehow to string and sent over url.
This is my current code:
- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSData *dataImage = UIImagePNGRepresentation(imgUser);
NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/DataTransfer /SetUserProfileImage?EMP_ID=%#&"
"image=%#&imageName=%#",
appDelegate.ServerAddress,
appDelegate.UserId,
theNSString,
strName]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSURLResponse* response = nil;
NSError* resultError = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&resultError];
NSString *strResult = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
BOOL imgResponse = [strResult boolValue];
[strResult release];
return imgResponse;
}
I get an error saying that the NSURL is "". Can't seem to build a correct URL. I know that the service itself converts this string to an image again.
UPDATE:
- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *url = [NSString stringWithFormat:#"%#/DataTransfer/SetUserProfileImage",appDelegate.ServerAddress];
NSData *data = UIImagePNGRepresentation(imgUser);
NSString * boundary = #"tweetPhotoBoundaryParm";
NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 1024];
name=\"EMP_ID\"\r\n\r\n%#", #"100-01"];
NSString * boundaryString = [NSString stringWithFormat:#"\r\n--%#\r\n", boundary];
NSString * boundaryStringFinal = [NSString stringWithFormat:#"\r\n--%#--\r\n", boundary];
[postData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"image\";\r\nfilename=\"media.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:[boundaryStringFinal dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
//[theRequest addValue:#"www.tweetphoto.com" forHTTPHeaderField:#"Host"];
NSString * dataLength = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest addValue:dataLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:(NSData*)postData];
NSURLConnection * theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
webData =[[NSMutableData data] retain];
}
else
{
NSLog(#"%#",#"Could not connect to the network");
}
return false;
}
Objective-C
-(void)saveImageToServer
{
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"yourImage"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"Your URL HERE";
// set your Image Name
NSString *filename = #"YourImageFileName";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Swift
// COnvert Image to NSData
var dataImage: NSData = UIImageJPEGRepresentation(UIImage(named: "yourImage"), 1.0)
// set your URL Where to Upload Image
var urlString: String = "Your URL HERE"
// set your Image Name
var filename: String = "YourImageFileName"
// Create 'POST' MutableRequest with Data and Other Image Attachment.
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: urlString)!
request.HTTPMethod = "POST"
var boundary: String = "---------------------------14737809831466499882746641449"
var contentType: String = "multipart/form-data; boundary=\(boundary)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var postbody: NSMutableData = NSMutableData.data()
postbody.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData("Content-Disposition: form-data; name=\"userfile\"; filename=\"\(filename).jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(String.stringWithString("Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(NSData.dataWithData(dataImage))
postbody.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding))
request.HTTPBody = postbody
// Get Response of Your Request
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var responseString: String = String(data: returnData, encoding: NSUTF8StringEncoding)
NSLog("Response %#", responseString)
This approach has several problems.
1) Converting the raw bytes of a image into a string will never work.
NSData *dataImage = UIImagePNGRepresentation(imgUser);
NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];
Will fail. You will never be able to reconstruct dataImage from theNSString. You need to base 64 encode dataImage. Use something like this to do the base 64 encoding.
2) Don't put image data into a URL. You need to put the image data in a post body.
3) Don't use "application/x-www-form-urlencoded", use "multipart/form-data".
Updated after Comments
Sorry, but it looks like you have a lot of work to do in understanding your system.
In the example above, you added all the data to the URL query string, but did not add anything to the body of the message. In that example you set the content type to be "application/x-www-form-urlencoded".
Now you seem to think the POST needs to be in JSON. You need to find out how that should be done. How does that JSON message need to be attached? Before you said the data needed to be in the URL, is this still the case? If you need to attach the JSON message to the POST body, what does the content type of the POST need to be? What is the structure of the JSON message (all the key/value fields needed)?
Before anyone can help you, you need to find out exactly what's needed. There should be someone who can give you an accurate description of the HTTP message.

iOS YouTube Video Upload Error

I am trying to upload a video using Objective-C and YouTube API but it is not working and return error at last step. The error reads "User authentication required".
I am following this API document specifically the one which is without metadata. I got the authentication token with ClientLogin API
I checked authentication token with NSLog and it's there. I see the upload API also returns Upload URL but when I send HTTP PUT request to retrieved Upload URL, it returns an error mentioned above.
Here's Upload Code
- (bool) upload:(NSString *)file {
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSURL *url = [NSURL URLWithString:self.UploadURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"PUT"];
[request setValue:#"Content-Type" forHTTPHeaderField:#"application/octet-stream"];
[request setValue:#"Content-Length" forHTTPHeaderField:[NSString stringWithFormat:#"%ud", [fileData length]]];
[request setHTTPBody:fileData];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
I also tried the Direct Upload method but this always gives me Invalid Request error. Below is the code.
- (bool) directUpload:(NSString *)file {
NSString *title = [file lastPathComponent];
NSString *desc = #"This is test video.";
NSString *category = #"People";
NSString *keywords = #"video";
NSString *boundary = #"--qwerty";
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSData *fileData = [NSData dataWithContentsOfFile:file];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: application/atom+xml; charset=UTF-8\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"%#\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Type: video/mp4\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"Content-Transfer-Encoding: binary\n\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:fileData];
[postBody appendData:[[NSString stringWithFormat:#"%#", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:#"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.AuthToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.DeveloperKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:[file lastPathComponent] forHTTPHeaderField:#"Slug"];
[request setValue:[NSString stringWithFormat:#"multipart/related; boundary=\"%#\"", boundary] forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%ud", [postBody length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"close" forHTTPHeaderField:#"Connection"];
[request setHTTPBody:postBody];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
if (response == nil) {
return NO;
} else {
return YES;
}
}
i think you should check this :-
https://developers.google.com/youtube/2.0/developers_guide_protocol_video_feeds
and you also check this :-
http://urinieto.com/2010/10/upload-videos-to-youtube-with-iphone-custom-app/

NSURLConnection to upload file asynchonrously?

I'm kinda of new at ios development,
I've been reading and searching but cannot find a working example or an example of
how to upload a file from iphone to webserver asychronously..
I'm able to upload synchronously using
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
it works, but it blocks my main thread.
NSUrlConnection has this delegate (connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)
but I've no idea how to implement it.
Can someone please point me in the right direction?
I have managed to get uploading to work with NSURLConnection asynchronously with this:
-(NSURLRequest *)postRequestWithURL: (NSString *)url
data: (NSData *)data
fileName: (NSString*)fileName
{
// from http://www.cocoadev.com/index.pl?HTTPFileUpload
//NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:[NSURL URLWithString:url]];
//[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
NSString *myboundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",myboundary];
[urlRequest addValue:contentType forHTTPHeaderField: #"Content-Type"];
//[urlRequest addValue: [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundry] forHTTPHeaderField:#"Content-Type"];
NSMutableData *postData = [NSMutableData data]; //[NSMutableData dataWithCapacity:[data length] + 512];
[postData appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", fileName]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:data]];
[postData appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", myboundary] dataUsingEncoding:NSUTF8StringEncoding]];
[urlRequest setHTTPBody:postData];
return urlRequest;
}
usage is as follows:
NSURLRequest *urlRequest = [self postRequestWithURL:urlString
data:aVideo.msgvid
fileName:filename];
uploadConnection =[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
Threading is not necessary for this kind of problem. I would suggest you use the asynchronous functionality built into NSURLConnection:
NSURLConnection *connection = [NSURLConnection initWithRequest:request delegate:self];
[connection start];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Get your response, do stuff
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//Show error, retry, etc
}
EDIT: If you are really looking to upload a file and want to display a progress bar, then you should look at ASIHTTPRequest framework, which you can find more info on here: http://allseeing-i.com/ASIHTTPRequest/
For uploading a POST request with data using ASIHTTPRequest, you would do:
NSURL *url = [NSURL URLWithString:#"YOUR_URL_HERE"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"123" forKey:#"user_id"];
[request setData:someData withFileName:#"someData.jpg" andContentType:#"image/png" forKey:#"image"];
[request setProgressDelegate:self];
[request setDelegate:self];
[request startAsynchronous];
Again, refer to the link above for the framework and documentation. I highly recommend it.
You cant create new thread for that task:
[NSThread detachNewThreadSelector:#selector(upload:) toTarget:self withObject:data];
And when you will finish uploading, just call some implemented method in your main thread (for example uploaded):
[self performSelectorOnMainThread:#selector(uploaded) withObject:nil waitUntilDone:NO];