AFNetworking not uploading image - ios

I am trying to upload an image via AFnetworking. I am able to get the image url, and it does contact my server. However, it won't upload. The file upload folder is empty and when I get back my JSON response, it is "null"
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Request to save the image to camera roll
[library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
if (error) {
NSLog(#"error");
} else {
NSLog(#"url %#", assetURL);
NSData *data = [NSData dataWithContentsOfURL:assetURL];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingString:#"/image.jpg"];
[data writeToFile:path atomically:YES];
[self uploadPhoto:path];
// NSLog(path);
[self dismissModalViewControllerAnimated:NO];
}
}];
}
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": self.targetid};
NSURL *filePath = [NSURL fileURLWithPath:file];
[manager POST:#"http:/****/uploadpics.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
image url looks like this:
/var/mobile/Applications/FFCAE923-1115-4209-AB39-D9D1ACEB9CB7/Documents/yourLocalImage.png
I can't seem to figure out what am I doing wrong.. The script is fine because it works for android just as it is supposed to...
PHP:
$name = $_FILES['filename']['name'];
if (is_uploaded_file($_FILES['filename']['tmp_name'])){
if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES ['filename'] ['name'])) {
Echo $foname;
} else {
}
} else {
}

Your upload code names the file image but your script seems to expect filename. I haven't done any php for a while but I think they should match.
There is another method which allows you to specify more details about the part that you're appending to the form data so you probably need that to set the appropriate names.

Related

objective-c,How to send file as a parameter

I want to upload my image from my phone gallery to the server so I am not able to upload my program ,it runs successfully and shows print -
NSLog(#">>>>>>>>>> enter in ");
but it could not upload image on the server ,when I checked it in the app then there is no image ,and I also checked parameter, I think I am not sending proper file format in the parameter.
Please can anyone help me with proper file formate how to convert it
`
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)img
editingInfo:(NSDictionary *)editingInfo
{
[picker dismissModalViewControllerAnimated:YES];
NSURL *imagePath = [editingInfo objectForKey:#"UIImagePickerControllerReferenceURL"];
imageName = [imagePath lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
localFilePath = [documentsDirectory stringByAppendingPathComponent:imageName];
NSLog(#"localFilePath.%#",localFilePath);
}
- (IBAction)submitBtn:(id)sender
{
NSURL* url;
url = [NSURL URLWithString:UrlBasic];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONWritingPrettyPrinted];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
fileURL = [NSURL fileURLWithPath:localFilePath];
reqData=[[NSMutableDictionary alloc]initWithObjectsAndKeys:imageName1,#"image",#"addclassphotoactmobs",#"droot",schoolFolderA,#"schoolfolder",_choseGalleryTextF.text,#"gname",dividNum,#"classid",fileURL,#"uploadedfile",nil];
NSLog(#"reqData=%#",reqData);
[manager POST:UrlBasic parameters:reqData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { }
progress:nil
success:^(NSURLSessionTask *task, NSMutableDictionary *responseObject) {
NSLog(#" %#",responseObject);
NSLog(#">>>>>>>>>> enter in ");
[self.view makeToast:#"submitted ....."
duration:3.0
position:CSToastPositionCenter];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error-=%#",error);
// [self.view makeToast:#"Please check internet connection !"];
}];
}
[Updated with imageNameStr]
While uploading your image data, it is necessary to send Name of the file.To generate a file Name, Here I've used Date and time.
Add the Code below the Line NSLog(#"reqData=%#",reqData);
====================
You have missed the formData Code.
Where as the image is the actual image in the below code.
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyyMMddhhmmssSSS"];
NSString *imageNameStr = [NSString stringWithFormat:#"%#.jpg",[formatter stringFromDate:[NSDate date]]];
[sessionManager POST:appendURL
parameters:postParamDict
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if(image!=nil){
NSData * imageData = UIImageJPEGRepresentation(image,0.5f);
if(imageData!=nil){
[formData appendPartWithFileData:imageData
name:#"image"
fileName:imageNameStr
mimeType:#"image/jpg"];
}
}
}
progress:^(NSProgress * _Nonnull uploadProgress) {
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(#"%#",responseObject);
if(success)
success (responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#",error);
if(failure)
failure (error);
}]

AFNetworking get image if it is modified

I am using AFNetworking and download image if it is new image.
After I read though stackoverflow, currently, I am doing like this.
If the image is not modified, there will be cache in http header and I use that fact to check whether image is modified or not.
It is working well for most iOS. But, on iPhone 6s iOS 9.2.1, it always assume as new image.
How shall I detect whether image in server is modified already by using AFNetworking or may be NSUrlConnection?
- (void)downloadSplashScreenFromURL:(NSString *)urlStr
{
BOOL __block responseFromCache = YES; // yes by default
void (^requestSuccessBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^(AFHTTPRequestOperation *operation, id responseObject) {
// response was returned from the server, not from cache
NSString *assestName = [urlStr lastPathComponent];
////WRITE TO FILEPATH
NSString *filePath = [splashDirectory() stringByAppendingString:
[NSString stringWithFormat:#"/%#", assestName]];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
DLog(#"Splash : Splash image is empty");
NSData *pngData = UIImagePNGRepresentation(responseObject);
[pngData writeToFile:filePath atomically:YES];
return ;
}
if (responseFromCache) {
// response was returned from cache
DLog(#"SPLASH - RESPONSE FROM CACHE: %#", responseObject);
}
else {
DLog(#"SPLASH - NEW IMAGES FROM SERVER \n Response: %#", responseObject);
NSData *pngData = UIImagePNGRepresentation(responseObject);
[pngData writeToFile:filePath atomically:YES];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:USERDEFAULTS_SPLASH_SCREEN];
[[SplashHelper sharedInstance] showSplash:YES inWindow:[AppDelegate instance].window andSuccessBlock:^{
[[AppDelegate instance] startRunning];
}];
}
};
void (^requestFailureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^(AFHTTPRequestOperation *operation, NSError *error) {
NSInteger statusCode = operation.response.statusCode;
DLog(#"SPLASH - status code: %lu \nERROR: %#", (long)statusCode, [error localizedDescription]);
DLog(#"SPLASH - ERROR: %#", error);
};
DLog(#"Splash : CALL SPLASH SCREEN HELPER");
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation = [manager GET:urlStr
parameters:nil
success:requestSuccessBlock
failure:requestFailureBlock];
[manager.requestSerializer setTimeoutInterval:3.0f];
operation.responseSerializer = [AFImageResponseSerializer serializer];
[operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
// this will be called whenever server returns status code 200, not 304
responseFromCache = NO;
DLog(#"Splash : cachedResponse = %#", cachedResponse);
return cachedResponse;
}];
}
I'm using #import "UIImageView+AFNetworking.h" category in my app to load an image from my server to app. Its working great, whenever an an update made for images on server, it'll generate new URLs, thus when I request with new URLs, AFNetworking will not find a cached image and will load new images from server.
And you should also check this, How do I get cached image stored by AFNetworking's UIImageView category? - there comes requirement when you needs to look after for an image inside your app's cache area.

Upload video chuck downloaded from one server to another server using AFNetworking

I am making an app that will transmit data from glasses to the server for broadcasting.
Til now i am able to download data from glasses to my iPhone document directory.
now i want to upload that downloaded data to my server so that we can broadcast that data to our users.
My iPhone and glasses are connected with each other with the help of WiFi, and i am trying to upload downloaded data via cellular network.
So basically my concept is that download data from glasses and upload that to server.
I have try to make my iPhone as a server to that my back end team could download data from my iPhone.
I got success in this method but the problem is that for this process the client and server should be on same private ip networks.
so now we have left with only one way that we download TS chucks from glasses and same time upload the TS file to our server for broadcasting.
I am using NFNetworking to download video chucks from glasses "TS File" but not able to upload that chucks to my server.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xxx.xx.xx.x/abc/trunk/WebServices/app/webroot/xyz"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;
operation.outputStream = [NSOutputStream outputStreamWithURL:[NSURL URLWithString:#"http://abc.aa.a.a/xyz/trunk/WebServices/app/webroot/img/glasses/test/demo.ts"] append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSLog(#"Successfully downloaded file to %#", path);
// NSLog(#"download finished!");
if(_delegate && [_delegate respondsToSelector:#selector(ZBTM3U8SegmentDownloaderFinishDownload:)])
{
[_delegate ZBTM3U8SegmentDownloaderFinishDownload:self];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// NSLog(#"Error: %#", error);
}];
[operation start];
It goes in success state but data is not uploaded on server
server folder show empty.
- (void)postVideoOnServer {
NSDictionary *requestDict = #{ #"uniqueToken":#"101", #"user_id":#"102",};
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:_tsFileName];
NSData *selectedVideo = [NSData dataWithContentsOfFile:path];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation = [manager POST:#"http://xxx.x.x.xx/myi/public_html/WebServices/broad/axy" parameters:requestDict constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
[formData appendPartWithFileData:selectedVideo name:#"file" fileName:#"filename.ts" mimeType:#"video/quicktime"];
} success: ^(AFHTTPRequestOperation *operation, id responseObject)
{
NSInteger statusCode = operation.response.statusCode;
NSLog(#"Status Code ::%d", statusCode);
NSLog(#"Response ::%#", responseObject);
[self handleVideoServiceResponse:responseObject];
}
failure : ^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %# %#", operation.responseString, error);
}];
[operation start];
}
it always return request time out error.
Thanks in advance.
Are you sure NSData *selectedVideo is not nil? i doubt you mime type too? Just a suggestion try use MIME: video/MP2T, it should fix your problem.

Capture Upload Image Failed iOS

I m trying to upload image through AFNetworking.
Following is the way I try to save image in an array. Image uploading starts, but right after the 1.1% of upload it stops uploading without any error. No Idea what is happening.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *chosenImage = info[UIImagePickerControllerOriginalImage];
NSData *imageData=UIImagePNGRepresentation(chosenImage);
ImageObject *imageObject=[[ImageObject alloc]init];
imageObject.image=chosenImage;
imageObject.imageData=imageData;
imageObject.imageUploadStatus=FALSE;
imageObject.isUploaded=FALSE;
[imageObject setDescription:#""];
[imageDataArray addObject:imageObject];
}
After this I upload image with Following method.
-(void)uploadPicturesAndVides:(NSMutableArray *)_list descriptions:(NSMutableArray *)_description categoryID:(NSString *)_catID categoryName:(NSString *)_categoryName index:(NSInteger)_index{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[SettingValues getRSFToken] forHTTPHeaderField:#"_csrf"];
[manager.requestSerializer setValue:#"USER_Agent_Value" forHTTPHeaderField:#"User-Agent"];
NSString *imageUrl;
imageUrl=[NSString stringWithFormat:#"%#/user/upload/photo",BASE_SERVER_ADDRESS];
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for (ImageObject *object in _list) {
[tempArray addObject:[object description]];
}
NSString *descriptions;
descriptions=[tempArray componentsJoinedByString:#","];
NSDictionary *parameters = #{#"descriptionImage":descriptions,#"subcategoryId":_catID,#"subcategoryName":_categoryName,#"_csrf": [SettingValues getRSFToken]};
AFHTTPRequestOperation *op = [manager POST:imageUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSInteger count=_index;
for (ImageObject *object in _list) {
NSString *imageName = [NSString stringWithFormat:#"IMG00%zd.png",count];
[formData appendPartWithFileData:object.imageData name:#"files" fileName:imageName mimeType:#"image/png"];
}
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[SettingValues setImageUploadStatus:TRUE];
[self uploadingRequestSuccessfulWithObject:responseObject reqestName:#"picture" index:_index];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[op setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
[self goBackTouploadingControllerWithProgressResult:percentDone index:_index];
}];
cancelManager=op;
[op start];
}
Following is the image and its progress stays here! no success no failure. :(
Problem is that code works when I upload image through Camera Roll, But when I capture image, it did not.
I put a NSLog(#"progress updated(percentDone) : %f", percentDone); in Progress Block and I found the following logs
2015-02-07 13:07:22.854 APP_Name[2069:60b] progress updated(percentDone) : 0.002105
2015-02-07 13:07:22.858 APP_Name[2069:60b] progress updated(percentDone) : 0.004210
2015-02-07 13:07:22.860 APP_Name[2069:60b] progress updated(percentDone) : 0.006315
2015-02-07 13:07:22.861 APP_Name[2069:60b] progress updated(percentDone) : 0.008413
and then every thing stops.
In Failure block I put following log
NSLog(#"Error: %# ***** %#", operation.responseString, error);
Never executed :(

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