I want to upload an image from my iphone (from imagepicker) to my server (with an PHP-script). But how do I get the image from the imagepicker / ImageView to the script for upload?
Here is my database connection code:
NSString *brugernavn = [[NSUserDefaults standardUserDefaults] stringForKey:kBrugernavn];
NSString *maaltid = self.maaltid.text;
//NSString *rating = [segmentedControl titleForSegmentAtIndex:[segmentedControl selectedSegmentIndex]];
//NSString *rating = self.rating;
NSString *kommentar = self.kommentar.text;
NSString *place = self.place.text;
NSData *data = [NSData dataWithContentsOfFile:filepath];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"brugernavn=%#&&maaltid=%#&&kommentar=%#&&place=%#&&thumbnail=%#&&submit",brugernavn,maaltid,kommentar,place,data];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://example.com/upload.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
And here is my code for the imagepicker:
// KAMERA - Aktiverer kameraet ved tryk på knap
- (IBAction)useCamera:(id)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
_newMedia = YES;
}
}
// KAMERA - Aktiverer kamerarullen ved tryk på knap
- (IBAction)useCameraRoll:(id)sender {
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.SourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = #[(NSString *) kUTTypeImage];
imagePicker.allowsEditing = NO;
[self presentViewController:imagePicker animated:YES completion:nil];
_newMedia = NO;
}
}
// KAMERA - Sender valgt billede til imageView
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = info[UIImagePickerControllerMediaType];
[self dismissViewControllerAnimated:YES completion:nil];
if([mediaType isEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = info[UIImagePickerControllerOriginalImage];
_imageView.image = image;
if (_newMedia)
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image:finishedSavingWithError:contextInfo:), nil);
} else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
And here the imageView from my .h-file:
#property (strong, nonatomic) IBOutlet UIImageView *imageView;
And here is the defination of my upload-field on PHP:
$_FILES['thumbnail']['name']
The user should take a picture og choose from the cameraroll and then write some info like title, description, etc. for the upload and then upload the image and info the server with the PHP-script.
Please help me :o)
It has been a while since I used this, but it worked then :)
NSData *imageData = UIImagePNGRepresentation(bilden);
NSString *filename = [NSString stringWithFormat:#"bild%d%#", bildnr,#".png"];
NSString *urlString = #"http://extranet.pool.se/stockholmsmassan/rita_pa_vaggen/sparabild.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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 *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
// second parameter information
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"epost\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[epost dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r \n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// now lets make the connection to the web
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);
Related
I am uploading video on youtube using this code..
- (void)sendVideoFileMetadata:(NSDictionary *)videoMetadata
error:(NSError **)error
{
[self logDebug:#"Sending file info..."];
NSString *category = videoMetadata[kDDYouTubeVideoMetadataCategoryKey];
NSString *keywords = videoMetadata[kDDYouTubeVideoMetadataKeywordsKey];
NSString *title = videoMetadata[kDDYouTubeVideoMetadataTitleKey];
NSString *desc = videoMetadata[kDDYouTubeVideoMetadataDescriptionKey];
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:privacyStatus>unlisted</media:privacyStatus>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/action/GetUploadToken"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.authorizationToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:#"unlisted" forHTTPHeaderField:#"privacyStatus"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.developerKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:#"application/atom+xml; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%u", (unsigned int)xml.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]];
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypePrepare];
// Create error if there were
// problems creating a connection
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
}
}
- (BOOL)uploadVideoFile:(NSURL *)fileURL
error:(NSError **)error
{
NSString *boundary = #"AbyRvAlG";
NSString *nextURL = #"http://www.youtube.com";
NSData *fileData = [NSData dataWithContentsOfFile:[fileURL relativePath]];
_videoFileLength = [fileData length];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?nexturl=%#", self.uploadURLString, nextURL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableString *bodyString = [NSMutableString new];
// Add token
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendString:#"Content-Disposition: form-data; name=\"token\"\r\n"];
[bodyString appendString:#"Content-Type: text/plain\r\n\r\n"];
[bodyString appendFormat:#"%#", self.uploadToken];
// Add file name
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n", [fileURL lastPathComponent]];
[bodyString appendFormat:#"Content-Type: application/octet-stream\r\n\r\n"];
[bodyString appendFormat:#"privacyStatus: unlisted\r\n\r\n"];
// Create the data
[body appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Set the body
[request setHTTPBody:body];
// Create the connection
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypeUpload];
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
return NO;
}
return YES;
}
This working perfectly,
But the issue is video uploaded as Public, i want to upload it as Unlisted.
I have tried so many tag but not able to get success.
Used,
- privacy
- privacystatus
Can anyone let me know where should i add the tag and whats the tag?
Code snippet will be more helpful.
Just update xml by adding
<yt.accesscontrol>
and it will uplaoad video as unlisted
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>"
#"<yt:accessControl action='list' permission='denied'/>"
#"</entry>", title, desc, category, keywords];
I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
I want to Upload an image and in my code it is uploading correctly, But I want to send one user id along with the image in post, Please some one can explain.
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2;
self.profileImageView.clipsToBounds = YES;
dic= [[NSMutableDictionary alloc]init];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
NSData *imageData = [defaults10 dataForKey:#"image"];
UIImage *contactImage = [UIImage imageWithData:imageData];
profileImageView.image = contactImage;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id1 = [defaults objectForKey:#"ID"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)Pictureupload:(id)sender
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init] ;
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
// profileImageView.image = image;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSDate *currentDate = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSString* cleanedString = [[localDateString stringByReplacingOccurrencesOfString:#"." withString:#""]stringByReplacingOccurrencesOfString:#":" withString:#""];
NSString *cleanedString2 = [cleanedString stringByAppendingFormat:#"%d",1];
NSString *finalUniqueImageNAme ;
finalUniqueImageNAme = [cleanedString2 stringByAppendingString:#".jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 90);
NSString *urlString = #"http://vygears.com/tcdc-portfolio/Abdul/chat/Pupload_file.php";
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 *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
[self dismissModalViewControllerAnimated:true];
}
else
{
NSLog(#"Connection could not be made");
}
});
});
[picker dismissModalViewControllerAnimated:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
webdata =[[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"%#",error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
// NSString *responseString = [[NSString alloc]initWithData:webdata encoding:NSUTF8StringEncoding];
dic=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSLog( #"Success %#",dic);
NSString * res = [dic objectForKey:#"url"];
NSURL *imageURL = [NSURL URLWithString:res];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
// Update the UI
self.profileImageView.image = [UIImage imageWithData:imageData];
NSUserDefaults *defaults10 = [NSUserDefaults standardUserDefaults];
[defaults10 setObject:imageData forKey:#"image"];
[defaults10 synchronize];
});
});
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissModalViewControllerAnimated:YES];
}
I have done like this now it is working fine.
// ----------------------------------Upload Image --------
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n",finalUniqueImageNAme] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// ----------------------------------Passing user_id in Post--------
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:id1] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Successfully uploaded");
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Hi i am very beginner in Ios and in my project i need to send "Username" and "Password" and "UserImage" to server using NSURLConnection and for this i have inserted this three fields(username,password,userimage) in one Dictionary and i am posting this dictionary to server but using my below code details are not sending to server please help me what did i do here wrong
my code:-
#interface SendingImagesToServer ()
{
NSMutableData *body;
}
#end
#implementation SendingImagesToServer
- (void)viewDidLoad {
[super viewDidLoad];
NSData *imageData;
UIImage * image;
NSError *error = nil;
image = [UIImage imageNamed:#"friendship.jpg"];
imageData = UIImageJPEGRepresentation(image, 0.1f);
NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"James" ,#"username",
#"1234",#"Password",
imageData,#"image",
nil];
NSString *jsonString = [mainDict JSONRepresentation];
NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
body = [webbody mutableCopy];
NSString *urlstr = [NSString stringWithFormat:#"My url here"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
if(imageData == nil && error!=nil) {
NSLog(#"nil");
}
else
{
NSLog(#"not nill");
}
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Successfully sending to server");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error is %#",[error localizedDescription]);
}
#end
You create the request, but don't start it anywhere in your code. Also you don't create the NSURLConnection anywhere (at least not in the posted part).
The easiest way to achieve this would be to simply add this line at the end of your viewDidLoad method :
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You can read more here
So this is my attempt:
I first create an "Image picker" which allows me to take the video:
- (IBAction)takeVideo:(UIButton *)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
self.movieURL = info[UIImagePickerControllerMediaURL];
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)viewDidAppear:(BOOL)animated {
self.movieController = [[MPMoviePlayerController alloc] init];
self.movieController.controlStyle = MPMovieControlStyleNone;
[self.movieController setContentURL:self.movieURL];
[self.movieController.view setFrame:CGRectMake (15, 125, 292, 390)];
self.movieController.view.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.movieController.view];
[self.movieController play];
NSString *myString = [self.movieURL absoluteString];
//THE DATA IS RETURNING 0 :
NSData *videoData = [NSData dataWithContentsOfFile:myString];
NSLog(#"%#",[NSByteCountFormatter stringFromByteCount:videoData.length countStyle:NSByteCountFormatterCountStyleFile]);
[self setImageDataToSend:videoData];
}
- (void)moviePlayBackDidFinish:(NSNotification *)notification {
[[NSNotificationCenter defaultCenter]removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[self.movieController stop];
[self.movieController.view removeFromSuperview];
self.movieController = nil;
}
I am not receiving any data from the URL though?
I then try and upload it to my site:
-(IBAction)uploadvideotowebsite:(id)sender{
//you can use any string instead "com.mycompany.myqueue"
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mcompany.myqueue", 0);
//turn on
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
dispatch_async(backgroundQueue, ^{
PFUser *user = [PFUser currentUser];
NSString * url = [NSString stringWithFormat:#"http://******.co.uk/****/imageupload.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSMutableData *body = [[NSMutableData alloc]init];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *String = #"Content-Disposition: form-data; name=\"image\"; filename=\"";
NSString *String2 = #"video";
NSString *String3 = #".MOV\"\r\n";
NSString *connection1 = [String stringByAppendingString: String2];
NSString *done = [connection1 stringByAppendingString: String3];
[body appendData:[[NSString stringWithFormat:done] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: audio/basic\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:_imageDataToSend];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//Send the Request
NSData* returnData = [NSURLConnection sendSynchronousRequest: request
returningResponse: nil error: nil];
//serialize to JSON
if (!returnData){
return; // or handle no connection error here
}else{
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
//parsing JSON
bool success = [result[#"success"] boolValue];
if(success){
NSLog(#"Success=%#",result[#"msg"]);
//[self performSegueWithIdentifier:#"toshow" sender:self];
}else{
NSLog(#"Fail=%#",result[#"msg"]);
}
}
dispatch_async(dispatch_get_main_queue(), ^{
//turn off
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
});
});
}
I am receiving no errors. But I am receiving a file of size 0kb on my site.
Can anybody explain why I am getting no data from the video?
Can anybody explain why I am getting no data from the video?
Sure, here's your mistake:
NSString *myString = [self.movieURL absoluteString];
should be path
NSString *myString = [self.movieURL path];
NSData *videoData = [NSData dataWithContentsOfFile:myString];
NSLog(#"%#",[NSByteCountFormatter stringFromByteCount:videoData.length countStyle:NSByteCountFormatterCountStyleFile]);
Am trying to upload a videos to server. I have two choice to upload videos. First one is, Take video and upload it to server. Second one is, Choose video from photo library and upload it to server.
Step 1:
In this scenario, Take video and upload it to server is working good.
I got the response from server is "Return String: {"jsonstatus":"ok","message":"Thanks for your posting."}".
Now i try to get this video from server. In media_file it says "x.x.x.x/video/96b8954fbed797500da708fd7bad2261video.mov" - I played this video successfully.
Step 2:
But when i choose the video from photo library, it successfully choosed the video. Now i post this video to server.
I got the response from server is "Return String: {"jsonstatus":"ok","message":"Thanks for your posting."}".
Now i try to get this video from server. In media_file it says "Invalid File"
Am using to choose video is,
- (IBAction)act_UploadVideoBtn:(id)sender
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];
[self presentViewController:imagePicker animated:YES completion:NULL];
}
And Delegate method is,
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// movieURL = [info valueForKey:UIImagePickerControllerMediaURL];
//
// [picker dismissViewControllerAnimated:YES completion:NULL];
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
if (CFStringCompare ((__bridge CFStringRef) mediaType, kUTTypeMovie, 0) == kCFCompareEqualTo) {
NSString *moviePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
// NSLog(#"%#",moviePath);
movieURL=(NSURL*)[info objectForKey:UIImagePickerControllerMediaURL];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum (moviePath)) {
UISaveVideoAtPathToSavedPhotosAlbum (moviePath, nil, nil, nil);
}
}
[picker dismissViewControllerAnimated:YES completion:NULL];
}
Give any ideas to solve this issue.
Could you describe your server side? So far I understand that this may be a full url problem. Maybe snippets of your json? Perhaps look over your permissions on the folder you are writing into. If you are using ubuntu and lamp as a stack (noob i know) make sure it is r+w, but not exec.
//push video path to NSData
NSData *webData = [NSData dataWithContentsOfURL:movieURL];
NSURL *url = [NSURL URLWithString:#"http://www.example.com/upload_media.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"+++++ABck";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data;
boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"YOURFILENAME\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: video/quicktime\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];//video/quicktime for .mov format
[body appendData:[NSData dataWithData:webData]];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",response);
NSLog(#"%#",error);
/*Server code*/
move_uploaded_file($_FILES["file"]["tmp_name"],$upload_dir['basedir'].'YOUR_DIR']);