Same image saving to two separate fields? - ios

I have 2 image views (imageView & imageTwo) and four buttons (takePhoto and selectPhoto for each image view). Tapping each button displays the taken or selected photo in the corresponding image view. Great.
HOWEVER, I'm attempting to save the two photos taken to my database. For some reason, the first photo taken saves to my two different database fields (the same photo appears in both fields, instead of each different photo saving to the two separate fields). That said, the data seems to save correctly (see XML output).
Why is this? See code below (sorry for the lengthy post).
viewcontroller.m
//PHOTO ONE UPLOAD TAKE AND SELECT
- (IBAction)selectPhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
selectedImageView = self.imageView; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)takePhoto:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
selectedImageView = self.imageView; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)takePhotoTwo:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
selectedImageView = self.imageTwo; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)selectPhotoTwo:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
selectedImageView = self.imageTwo; // Add this
[self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = info[UIImagePickerControllerEditedImage];
selectedImageView.image = image;
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)saveButton:(id)sender {
//FIRST IMAGE DATA
NSData *imgData = UIImageJPEGRepresentation(self.imageView.image, 0.5);
NSMutableDictionary *file = [[NSMutableDictionary alloc] init];
NSString *base64Image = [imgData base64EncodedString];
[file setObject:base64Image forKey:#"file"];
NSString *timestamp = [NSString stringWithFormat:#"%d", (int)[[NSDate date] timeIntervalSince1970]];
NSString *imageTitle = _itemName.text;
NSString *filePath = [NSString stringWithFormat:#"%#%#.jpg",#"public://stored/", imageTitle];
NSString *fileName = [NSString stringWithFormat:#"%#.jpg", imageTitle];
[file setObject:filePath forKey:#"filepath"];
[file setObject:fileName forKey:#"filename"];
[file setObject:timestamp forKey:#"timestamp"];
NSString *fileSize = [NSString stringWithFormat:#"%lu", (unsigned long)[imgData length]];
[file setObject:fileSize forKey:#"filesize"];
//SECOND IMAGE DATA
NSData *secondimgData = UIImageJPEGRepresentation(self.imageTwo.image, 0.5);
NSMutableDictionary *secondfile = [[NSMutableDictionary alloc] init];
NSString *secondbase64Image = [secondimgData base64EncodedString];
[file setObject:secondbase64Image forKey:#"file"];
NSString *secondtimestamp = [NSString stringWithFormat:#"%d", (int)[[NSDate date] timeIntervalSince1970]];
NSString *secondimageTitle = secondtimestamp;
NSString *secondfilePath = [NSString stringWithFormat:#"%#%#.jpg",#"public://stored/", secondimageTitle];
NSString *secondfileName = [NSString stringWithFormat:#"%#.jpg", secondimageTitle];
[secondfile setObject:secondfilePath forKey:#"filepath"];
[secondfile setObject:secondfileName forKey:#"filename"];
[secondfile setObject:secondtimestamp forKey:#"timestamp"];
NSString *secondfileSize = [NSString stringWithFormat:#"%lu", (unsigned long)[secondimgData length]];
[secondfile setObject:secondfileSize forKey:#"filesize"];
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"File uploaded!");
//FIRST IMAGE FILE
[file setObject:[responseObject objectForKey:#"fid"] forKey:#"fid"];
[file removeObjectForKey:#"file"];
fid = [responseObject objectForKey:#"fid"];
NSLog(#"%#",responseObject);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: [NSString stringWithFormat:#"%#", fid] forKey:#"fid"];
NSLog(#"%#", fid);
NSDictionary *fidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:dict] forKey:#"und"];
[nodeData setObject:fidLangDict forKey:#"field_photo"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
[DIOSFile fileSave:file success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"File uploaded!");
//SECOND IMAGE FILE
[secondfile setObject:[responseObject objectForKey:#"fid"] forKey:#"fid"];
[secondfile removeObjectForKey:#"file"];
fid = [responseObject objectForKey:#"fid"];
NSLog(#"%#",responseObject);
NSMutableDictionary *secondDict = [NSMutableDictionary dictionary];
[secondDict setObject: [NSString stringWithFormat:#"%#", fid] forKey:#"fid"];
NSLog(#"%#", fid);
NSDictionary *secondfidLangDict = [NSDictionary dictionaryWithObject:[NSArray arrayWithObject:secondDict] forKey:#"und"];
[nodeData setObject:secondfidLangDict forKey:#"phototwo"];
[DIOSNode nodeSave:nodeData success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Node saved!");
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main_iPad" bundle:nil];
ipadaccountViewController *AccountViewController = (ipadaccountViewController *)[storyboard instantiateViewControllerWithIdentifier:#"MyAccount"];
[self.navigationController popViewControllerAnimated:TRUE];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Node did not save!");
}];
XML Data upon save:
<field_photo>
<und is_array="true">
<item>
<fid>265</fid>
<uid>5</uid>
<filename>phone.jpg</filename>
<uri>public://stored/phone_1.jpg</uri>
<filemime>image/jpeg</filemime>
<filesize>161858</filesize>
<status>1</status>
<timestamp>1460264800</timestamp>
<rdf_mapping/>
<alt/>
<title/>
<width>1536</width>
<height>1536</height>
</item>
</und>
</field_photo>
<phototwo>
<und is_array="true">
<item>
<fid>266</fid>
<uid>5</uid>
<filename>phone.jpg</filename>
<uri>public://stored/phone_2.jpg</uri>
<filemime>image/jpeg</filemime>
<filesize>161858</filesize>
<status>1</status>
<timestamp>1460264800</timestamp>
<rdf_mapping/>
<alt/>
<title/>
<width>1536</width>
<height>1536</height>
</item>
</und>
</phototwo>

I think in the second [DIOSFile fileSave... it should be secondfile instead of file.

Related

Problems sharing document on IOS when the user doesn't have an email account on the device

I have a problem when I try to share a pdf document using UIActivityViewController via email.
When the user has configured his email sharing works well, the document it appears attached, but when the user doesn't have an email account previously configured it prompts the user to chose an email provider, if I configure the email account the new email it appears but without the document attached. If I try again with the email configured it works well.
I have test it on iOS 9 and 10 and it gives me the same problem.
This is my code on Objective C:
NSString *file = [NSString stringWithFormat:#"file://%#", items[0][#"source"]];
NSURLRequest *urlRequestToLoad = [NSURLRequest requestWithURL:[NSURL URLWithString:file] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSArray *sharingItems = #[items[0][#"filename"], [urlRequestToLoad URL]];
UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingItems applicationActivities:nil];
[activityController setValue:#"Your email Subject" forKey:#"subject"];
[self.viewController presentViewController:activityController animated:YES completion:nil];
Any idea of what I'm doing wrong?
is! Simple solution :) Download and attach file. If you are loading PDF in webview earlier, please find the comment below.
-(void)print:(NSString*)subject withFileName:(NSString*)fileName webFileURL:(NSURL*)webURL{
if ([UIActivityViewController class]) {
if (subject) {
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *title = [fileName stringByReplacingOccurrencesOfString:#" " withString:#"_"];;
title = [NSString stringWithFormat:#"%#.pdf",title];
NSString * filePath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",title];
// Showing spinner
NSURLRequest *request = [NSURLRequest requestWithURL:webURL];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// Close the spinner
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^ {
/* Set this available field on the activity controller */
NSMutableArray *items = [NSMutableArray array];
if (data) {
[items addObject:[NSURL fileURLWithPath:filePath]];
}
// Print webView
// {
// [items addObject:[self.webViewInstance viewPrintFormatter]];
// }
if (webURL) {
[items addObject:[NSString stringWithFormat:#"%# - %#",subject, [webURL absoluteString]];
}
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
[activityViewController setValue:subject forKey:#"subject"]; // Set the mail subject.
// If you are not handle it. It will crash in iPad
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
activityViewController.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popPC = activityViewController.popoverPresentationController;
popPC.sourceView = self.view;
popPC.sourceRect = kSharePopArea;
popPC.permittedArrowDirections = UIPopoverArrowDirectionAny;
}
[self presentViewController:activityViewController animated:YES completion:nil];
});
}
}];
}
}
}
NSString *content = #"write text here";
NSError* lError;
NSMutableArray *items = [NSMutableArray array];
if ([NSData dataWithContentsOfURL:fileUrl options:NSDataReadingMappedAlways error:&lError]) // Local file
{
[items addObject:fileUrl];
}
if(content) {
[items addObject:content];
}
if(imagename && [UIImage imageNamed:#"imagename"]) {
[items addObject:[UIImage imageNamed:#"imagename"]];
}
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
// Add email subject.
[activityViewController setValue:#"Your email Subject" forKey:#"subject"];
// If you are not handle it. It will crash in iPad
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
activityViewController.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popPC = activityViewController.popoverPresentationController;
popPC.sourceView = self.view;
popPC.sourceRect = kSharePopArea;
popPC.permittedArrowDirections = UIPopoverArrowDirectionAny;
}
[self presentViewController:activityViewController animated:YES completion:nil];

Error while uploading images taken from camera to server AFNetworking 3.0

I am using AFNetworking to send images to my server. When I pick images from Gallery every thing works fine. But when I pick image using Camera, the server sends me an error that its an invalid image.
Using UIImagePickerController to pick images from camera.
Code
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager.requestSerializer setValue:API_KEY_VALUE forHTTPHeaderField:API_KEY];
NSMutableURLRequest * request = [manager.requestSerializer multipartFormRequestWithMethod:#"POST" URLString:URL parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
UIImage *image = nil;
for (int i=0; i < [imagesArr count]; i++)
{
image = [imagesArr objectAtIndex:i];
// image = [UIImage imageNamed:[NSString stringWithFormat:#"%d", i+1]];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString * paramName = [NSString stringWithFormat:#"scrappygram_image[%d]",i];
[formData appendPartWithFileData:imageData name:paramName
fileName:[NSString stringWithFormat:#"image_%d",i]
mimeType:#"image/jpeg"];
}
} error:nil];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse response, id responseObject, NSError error)
{
if (error)
{
NSLog(#"Error: %#", error.localizedDescription);
[self.delegate apiFailedWithError:error andType:type];
} else
{
NSLog(#"%#", responseObject);
[self.delegate apiSuccessWithRespoonseDictionary:responseObject andType:type];
}
}] resume];
Did Finish Launching with options Code
[GMSPlacesClient provideAPIKey:GMSPLACES_API_KEY];
[GMSServices provideAPIKey: GMSPLACES_API_KEY];
[[IQKeyboardManager sharedManager] setEnable:YES];
[[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:true];
[self settingsForRemoteNotifications];
[[NSUserDefaults standardUserDefaults] setValue:DEBUG_API_FAILED_ERROR_SHOW_YES forKey:DEBUG_ERROR_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
return YES;
Use below method when uploading through camera.
- (void)selectPhotoFromCamera
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
//imagePickerController.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
imagePickerController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, nil];
imagePickerController.delegate = self;
[self presentViewController:imagePickerController animated:YES completion:nil];
}

Getting delay to see next view controller ,see detail in post?

I have one login screen after that it will move to next view controller which have i have used some networks like http,json to get data from server. when i enter login username/password then if i click login button its getting delay to 8 seconds after that only it moving to next view controller.Still that my login screen alone showing for 8 seconds and then only it move to next view controller.
Here my login controller.m:
#implementation mainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_username.delegate = self;
_password.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:#"reg"]) {
NSLog(#"no user reg");
_logBtn.hidden = NO;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
_username.text = nil;
_password.text = nil;
}
- (IBAction)LoginUser:(id)sender {
if ([_username.text isEqualToString:#"sat"] && [_password.text isEqualToString:#"123"]) {
NSLog(#"Login success");
[self performSegueWithIdentifier:#"nextscreen" sender:self];
}
else {
NSLog(#"login was unsucess");
// Alert message
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"wrong"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Here my nextcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
// here only i am getting data from server
[self getdata];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
}
Help me out. If my question din't understand.I can tell more about my post. And in my nextcontroller.m [self getdata] is i am getting data from server url.Thanks
My get data:
-(void)getdata {
NSString *userName = #“users”;
NSString *password = #“images”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://porterblog/image/file”;
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError * error;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#“birds”];
[titleArray addObject:[NSString stringWithFormat:#" birds(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"owl”];
[titleArray addObject:[NSString stringWithFormat:#" Owl(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pensq”];
[titleArray addObject:[NSString stringWithFormat:#" Pensq(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#“lion”];
[titleArray addObject:[NSString stringWithFormat:#" lion(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
NSString *error1;
returnData = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(returnData ) {
if ([returnData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
}
EDITED:
`- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
self.dataSourceForSearchResult = [NSArray new];
titleArray = [NSMutableArray array];
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
self.navigationItem.hidesBackButton = YES;
});
});
}`
You're getting your data using main thread you need do to that in background then invoke the code you need (as i see is reload collectionView)
I assume that because you didn't show the getdata method code
If that the case you can use this code:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
It's mean that your VC will show immediately but the collectionView fill after you finish load the data, you can put some old data while loading like Facebook app (you see latest retrieved posts until finish loading].
Edit:
In your code you replace viewdidload method in nextController with next code:
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}

Ui view freez for long time

I am working on afnetworking, i have web service that takes too much time to load data and i want that UI do not freeze, i used this tutorial to run webservice on background so that i can work on other views as well, but not sucess till yet.
-(void) getArticles :(NSString*)stateAbbre completionHandler:(void (^)(id array))success
{
[MyCommonFunctions showGlobalProgressHUDWithTitle:#"Loading"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/depilexs/get_articles_ios.php"];
NSLog(#"%#",link);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:link parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSDictionary *returnedDealDict = responseObject ;
NSArray *returnArray = [returnedDealDict objectForKey:#"Result"];
for(NSDictionary *dealDict in returnArray)
{
ArticlesDC *articles = [[ArticlesDC alloc] init];
articles.articlesID = [[dealDict objectForKey:#"id"]intValue ];
articles.articleTitle = [dealDict objectForKey:#"title" ];
articles.articleDetail = [dealDict objectForKey:#"details" ];
articles.articleDate = [dealDict objectForKey:#"date" ];
articles.articlePic = [dealDict objectForKey:#"pic" ];
articles.articleThumbPath = [dealDict objectForKey:#"thumb_path" ];
articles.articleStatus = [dealDict objectForKey:#"status" ];
[dataArray addObject:articles];
[MyCommonFunctions dismissGlobalHUD];
}
success(dataArray);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error occured while loading data.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
and in my view did load method
[self getArticles:nil completionHandler:^(id array) {
articlesArray = array;
[tblView reloadData];
for (ArticlesDC *article in articlesArray)
{
NSString *stringWithoutSpace = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articleThumbPath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringWithoutSpace]];
UIImage *imgOne = [UIImage imageWithData:imageData];
NSString *stringforImg = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articlePic] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageDta = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringforImg]];
UIImage *imgTwo = [UIImage imageWithData:imageDta];
[dbHandler insertArticlesIntoSqlite:article.articleTitle andDetail:article.articleDetail anddate:article.articleDate andImage:[MyCommonFunctions saveImageInDocuments:imgTwo] andThumb:[MyCommonFunctions saveImageInDocuments:imgOne]];
[defaults setInteger:1 forKey:#"getArticlesOffline"];
[defaults synchronize];
}
}];
The problem is not AF, it's that at the end of that process you call dataWithContentsOfURL twice and this runs directly on the main thread to download some images. You need to move that download to a background thread.

How to upload the image/photo to a server using AFNetworking?

I am trying to upload the image/video to a webserver for iOS.
The uploading part of this server works fine. I checked it with Android version and I have already implemented the uploading method in Android app.
So I have found some codes for iOS on the stackoverflow.com
First, I am using the following code for uploading image.
But I can't upload at all and get the following result. I am using XCode6.1 on iOS8 SDK.
Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x7fe24348d0b0 {NSUnderlyingError=0x7fe2434be120 "The request timed out.", NSErrorFailingURLStringKey=ServerURL, NSErrorFailingURLKey=ServerURL, NSLocalizedDescription=The request timed out.}
Here are the codes that I am using.
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
Certainly, the server works fine.
I have definitely tested with Android code.
So I'd like to know the exact code for iOS.
Thank you
This is my working code uploading an image to the server using AFNetworking:
+ (void)uploadImage:(UIImage *)image
ForUser:(WECUser *)user
withSuccessBlock:(void (^)(NSDictionary *response))resultBlock
faliureBlock:(void (^)(NSError *error))faliureBlock {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyyMMddHHmmss";
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName =
[NSString stringWithFormat:#"user_image_%#.jpg", dateString];
NSDictionary *dictionary = #{
#"user_id" : user._id,
#"resource_id" : user._id,
#"functioncode" : #"2000",
#"app_id" : [WECURLGenerator stringOfAppID],
#"file_name" : fileName
};
NSURLRequest *request = [[AFHTTPRequestSerializer serializer]
multipartFormRequestWithMethod:
#"POST" URLString:[WECURLGenerator stringOfImageUploadingBaseURL]
parameters:dictionary
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData
appendPartWithFileData:UIImageJPEGRepresentation(image, 0.6)
name:#"file1"
fileName:fileName
mimeType:#"jpg"];
} error:(NULL)];
AFHTTPRequestOperation *operation =
[[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,
id responseObject) {
NSDictionary *resultDict =
[NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableLeaves
error:nil];
resultBlock(resultDict[#"record"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
faliureBlock(error);
}];
[operation start];
}
Hope this helps.
Your code looks fine, I am using same code for uploading an image using AFNetworking. But you haven't mentioned how you are picking the image. Because you can not upload an image directly like:
UIImage *image = [UIImage imageNamed:#"sample.png"];
Are you using UIImagepickerController for picking your image?
If YES than see my code;
-(IBAction)chooseImg:(id)sender{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
picker = [[UIImagePickerController alloc]init];
picker.allowsEditing = NO;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
else{
picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.allowsEditing = YES;
picker.delegate = self;
picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self.navigationController presentViewController:picker animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSURL *name = [info objectForKey:UIImagePickerControllerReferenceURL];
image = [info objectForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset *imageAsset){
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSDictionary *metadata = imageAsset.defaultRepresentation.metadata;
NSLog(#"Meta:%#",metadata);
NSString *str = [imageRep filename];
txtImg.text = str;
};
ALAssetsLibrary *assetLib = [[ALAssetsLibrary alloc]init];
[assetLib assetForURL:name resultBlock:resultBlock failureBlock:nil];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
NOTE: Here I used metadata to display name of the image,it's not necessary you can skip this.
Than in uploading part:
NSString* serverURL = #"http://www.myserver.com/file/postMedia.php";
//UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSDictionary *param = #{#"userID":#"master",
[manager POST:serverURL parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"uploadedfile_thumb" fileName:#"photo.jpg" mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
....
});
return;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
....
});
This works for me uploading an image.
Hope it works for you.

Resources