Uploading NSData image via POST in iOS - ios

i have a form that contains some person information and an image. i tried to save information in post using this function and it work well :
- (void)Inscription:(NSArray *)value completion:(void (^)( NSString * retour))block{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSArray *Param_header = #[#"username", #"password", #"email",#"first_name", #"last_name",#"image"];
// NSArray *Param_value = #[#"ali", #"aliiiiiiii", #"ali.ali#gmail.com",#"ali",#"zzzzz"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: [NSString stringWithFormat:#"http:// /Messenger/services/messenger_register"]]];
NSString *aa=[self buildParameterWithPostType:#"User" andParameterHeaders:Param_header ansParameterValues:value];
[request setHTTPBody:[aa dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(#"Server Error : %#", error);
} else {
NSError *error = Nil;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
block([NSString stringWithFormat:#"%#", [jsonObjects objectForKey:#"message"]]);
}
}
];
}
No, i want to send the photo taked, i convert it to NSData first :
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *imag= [info objectForKey:#"UIImagePickerControllerOriginalImage"];
imag = [imag scaleAndRotateImage:imag];
CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 25*1024;//was 250x1024
NSData *imageData = UIImageJPEGRepresentation(imag, compression);
while ([imageData length] > maxFileSize && compression > maxCompression)
{
compression -= 0.1;
imageData = UIImageJPEGRepresentation(imag, compression);
}
NSData _D_ImageData = imageData;
And i tried to do this to send it to server but image c'ant be uploaded:
[web Inscription:Param_value completion:^(NSString *retour) {
CustomPrpgress.hidden=true;
NSLog(#" eee %# ",retour);
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:retour message:#"" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}];
Can someone help me, i'm beginner and this is my first time. thank you

My code work fine, i made a mistake in the php file

Related

I need to want how to Post/Upload a recorded or selected video to server using binary formate and mp4 type in objective c

Hi I just used image picker view to record a video and convert the video formate mov to mp4 and change NSData for posting. But it is not working I get 415 error some times 500 errors. Please check below code for how I implemented. Anybody can guid or help me for this issue.
if I need to check my server side team , they test with postman it is working well when I am implement of below code it is not working if may did any mistakes please guid me thank you
-(void)camerabuttonHandlerqas{
UIAlertController * picker = [UIAlertController alertControllerWithTitle:#"Pick an image using" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
imagePicker.delegate = self;
UIAlertAction* cancel = [UIAlertAction actionWithTitle:#"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { }];
UIAlertAction* takeVideo = [UIAlertAction actionWithTitle:#"TakeVideo" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
imagePicker.view.tag = 100;
[self presentViewController:imagePicker animated:YES completion:nil]; }];
[picker addAction:picture];
[picker addAction:cancel];
picker.view.tintColor = [UIColor grayColor];
[self presentViewController:picker animated:YES completion:nil];
}
#pragma mark - <UIImagePickerControllerDelegate>
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
videoURL = info[UIImagePickerControllerMediaURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* videoPath = [NSString stringWithFormat:#"%#/test_%d.mp4", [paths objectAtIndex:0],arc4random_uniform(1000)];
NSURL *outputURL = [NSURL fileURLWithPath:videoPath];
[self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
{
switch (exportSession.status) {
case AVAssetExportSessionStatusFailed:
NSLog(#"status failed");
break;
case AVAssetExportSessionStatusCompleted:{
NSLog(#"status success %# ",videoPath);
NSMutableDictionary *data = [NSMutableDictionary new];
videoURL = info[UIImagePickerControllerMediaURL];
[data setObject:[self generatePostDataForData:[NSData dataWithContentsOfFile:videoPath]] forKey:#"SelectedvideoURL"];
imagePickerIsSelected = YES;
[self postData:data];
break;
}
}];
[picker dismissViewControllerAnimated:YES completion:nil]; }
- (NSData *)generatePostDataForData:(NSData *)uploadData
{ // Generate the post header:
NSString *post = [NSString stringWithCString:"--AaB03x\r\nContent-Disposition: form-data; name=\"upload[file]\";
filename=\"somefile\"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: binary\r\n\r\n" encoding:NSASCIIStringEncoding];
// Get the post header int ASCII format:
NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Generate the mutable data variable:
NSMutableData *postData = [[NSMutableData alloc] initWithLength: [postHeaderData length] ];
[postData setData:postHeaderData];
// Add the image:
// Add the closing boundry:
[postData appendData: [#"\r\n--AaB03x--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
// Return the post data:
return postData;
}
-(void) postData:(NSData *)data
{
service = [NSString stringWithFormat:#"http://1.1.1.1:8080/testing/postapi/photoUpload/uploadVideo?videoName=video_%d&type=mp4",arc4random_uniform(1000)]
delegate = delegateInstance;
service = [service stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLFragmentAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:service]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
[request setValue:#"mp4/MOV" forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
// add image data
if (videoData) {
[body appendData:videoData];
}
// setting the body of the post to the reqeust
[request setHTTPBody:videoData];
// set URL
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
} }]; [dataTask resume]; }
415 error media type error check your server data type on which u r storing NSDATA.
I got solution that code is absolutely right and no need to change media type to mp4 if server side accept .mov type and please discuss with server side then have to change content type, and take file like as a one data then its working for me
Thank you.

MWphotobrowser - Fetch Images from Json

I'm trying to figure out how to get MWphotobrowser to fetch photo, photo caption, photo thumbnail etc. from a json file an extermal server.
In viewDidLoad, I have this code:
- (void)viewDidLoad {
NSURL *url = [NSURL URLWithString:#"https://s3.amazonaws.com/mobile-makers-lib/superheroes.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[super viewDidLoad];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSLog(#"Back from the web");
}];
NSLog(#"Just made the web call");
}
In Case3 MWphotobrowser's Menu.m, I have the following code:
case 3: {
photo.caption = [self.result valueForKeyPath:#"name"];
NSArray * photoURLs = [self.result valueForKeyPath:#"avatar_url"];
NSString * imageURL = [photoURLs objectAtIndex:indexPath.row];
[photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:imageURL]]];
enableGrid = NO;
break;
}
Incase you missed it, the JSON file I'm using is https://s3.amazonaws.com/mobile-makers-lib/superheroes.json
Nothing I tweak seems to make it work, any ideas how to fix this?
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
// here make sure ur response is getting or not
if ([data length] >0 && connectionError == nil)
{
// DO YOUR WORK HERE
self.superheroes = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &connectionError];
NSLog(#"data downloaded.==%#", self.superheroes);
}
else if ([data length] == 0 && connectionError == nil)
{
NSLog(#"Nothing was downloaded.");
}
else if (connectionError != nil){
NSLog(#"Error = %#", connectionError);
}
}];
in here u r getting the response from server is NSArray -->NSMutableDictionary` so
Case scenario is
case 3: {
NSDictionary *superhero = [self.superheroes objectAtIndex:indexPath.row];
photo.caption = superhero[#"name"];
NSString * imageURL = superhero[#"avatar_url"];
// NSArray * photoURLs = superhero[#"avatar_url"];
[photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:imageURL]]];
enableGrid = NO;
break;
}
ur final out put is

block not being called on the other end

i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(
I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?

load images into cache and display into UIImageView

how can i display image into UICollectionView using Cache and display large image into another
View on UICollectionView didSelect. Here both large and thumb image on CollectionView so next view large image not blank.using EMAsyncImageView
NSURL *url = [NSURL URLWithString:#"http://leewayinfotech.com/mobile/girlwallpaper/api.php?category=abstract&device=i5&hits=all"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(#"Response String=%#",responseString);
NSError *jsonError;
NSData *trimmedData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:trimmedData options:NSJSONReadingAllowFragments error:&jsonError];
if (jsonError) {
NSLog(#"JSON parse error: %#", jsonError);
return;
}
obj_Array=[[NSMutableArray alloc] init];
obj_Array=[json objectForKey:#"wallpaper"];
//NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.thumb_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.device_img_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
imgPage.imgNo_Array=[NSMutableArray arrayWithCapacity:[obj_Array count]];
for (int i=0; i<[obj_Array count]; i++) {
ImgClass *obj_Class=[[ImgClass alloc] init];
obj_Class.main_id=[[[obj_Array objectAtIndex:i] valueForKey:#"id"] integerValue];
[obj_Class.thumb_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image_thumb"]];
[obj_Class.device_img_Array addObject:[[[obj_Array objectAtIndex:i] objectForKey:#"images"] objectForKey:#"image2"]];
NSLog(#"Thumb-->%#\n\nDevice-->%#",[obj_Class.thumb_img_Array description],[obj_Class.device_img_Array description]);
[appDelg.my_Array addObject:obj_Class];
}
you use the EGOImageView for image caching support.
You can use SDWebImage.Using SDWebImage you can set image using imageURLString like below with CacheType.
[yourImgView setImageWithURL:[NSURL URLWithString:imageURLString]
placeholderImage:[UIImage imageNamed:#"noimage.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
if (!error && image)
{
}
}];
Hope it will helps you..

iOS async task freezes

I have an app which does an async post to a server. Then it decodes the json and returns the message from the server. I put a few debugging log entries in my code, so I know that the response from the server, as well as the decoding of the json are instantaneous. The problem is that after the json is decoded, the async task runs for about 6 seconds before it calls the next event (Showing the popup dialog).
- (IBAction)register:(id)sender {
[self startPost]; // Starts spinner animation
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doPost]; // performs post
});
}
-(void)doPost
{
#try {
NSString *post =[[NSString alloc] initWithFormat:#"request=register&platform=ios&email=%#&password=%#",self.email.text,self.password.text];
//NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://site.com/api.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"Response ==> %#", responseData);
NSData *responseDataNew = [responseData dataUsingEncoding:NSUTF8StringEncoding];
NSError* error = nil;
NSDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:responseDataNew options:NSJSONReadingMutableContainers error:&error];
if ( error ){
[self alertStatus:#"Unknown response code from server" :#"Whoops!"];
NSLog(#"Response ==> %#", responseData);
[self postDone];
}else{
if ([myDictionary[#"error"] isEqualToNumber:(#1)])
{
NSLog(#"ERROR DETECTED");
[self alertStatus:myDictionary[#"message"]:#"Whoops!"];
[self postDone];
}
else
{
[self alertSuccess];
[self postDone];
}
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Whoops!"];
[self postDone];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Registration Failed." :#"Whoops!"];
[self postDone];
}
}
-(void)startPost
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.email.enabled = false;
self.password.enabled = false;
self.confirm.enabled = false;
self.cancelButton.enabled = false;
}
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView setTag:0];
[alertView show];
}
- (void) alertSuccess
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Success!"
message:#"You have been successfully registered."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
[alertView setTag:1];
[alertView show];
}
-(void)postDone
{
self.registerButton.hidden = false;
self.spinner.hidden = true;
self.loadingText.hidden = true;
//[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.email.enabled = true;
self.password.enabled = true;
self.confirm.enabled = true;
self.cancelButton.enabled = true;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{if (alertView.tag == 1)
{
[self dismissViewControllerAnimated:YES completion:nil];
}}
The alertStatus and alertSuccess functions just pop up a message box briefly.
When I run the code, I purposefully enter bad information so the log says "ERROR DETECTED". The problem is that it takes another 6 seconds before anything happens after that.
After you have called:
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
and obtained the data, you should switch back to the main thread to use it. This is because all UI updates must be done on the main thread.
So, all that code after you get the data should be moved to a new method and called as:
dispatch_async(dispatch_get_main_queue(), ^{
[self handleData:urlData withResponse:response error:error];
}
And you should also put the exception catch code inside dispatch_async(dispatch_get_main_queue(), ^{ because you try to update the UI there too...

Resources