In my app I'm using RESTKit, so my AFNetworking version isn't the newest. I'm not sure how to check the version of it.
I want to download a picture from my server, and because the response is a jpg file, I'm using AFNetworking. On the first download of the image, it works well. Then I delete the image on the server and upload a new image with the same name. Then if I delete the image in the app and re-download it. In this scenario I still get the old picture from the first time I downloaded.
This is my code:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://myserver.com"]];
[client setAuthorizationHeaderWithUsername:name password:password];
[client getPath:[NSString stringWithFormat:#"profile-images/%#.jpg", user.name] parameters:#{} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"SUCCES");
NSData *imageData = responseObject;
self.tmpImage = [UIImage imageWithData:imageData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"FAIL");
self.tmpImage = [UIImage imageNamed:#"myImage.png"];
}];
It looks to me like the app "remembers" the first request I sent to the server when I downloaded the image. And then when I re-download it, it gives me the old picture. Does anyone know how to solve it?
I finally got this to work with using NSMutableURLRequest. When creating the request I set the cachePolicy to NSURLRequestReloadIgnoringLocalCacheData. Meaning: request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
Here is the code for sending the request to the server:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://server.com"]];
[client setAuthorizationHeaderWithUsername:name password:password];
NSMutableURLRequest *request = [client requestWithMethod:#"GET" path:[NSString stringWithFormat:#"profile-images/%#.jpg", user.name] parameters:nil];
request.timeoutInterval = 10;
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
AFImageRequestOperation *operation;
operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:^UIImage *(UIImage *image) {
NSLog(#"block");
return image;
} success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(#"SUCCES");
self.tmpImage = image;
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(#"FAIL");
self.tmpImage = [UIImage imageNamed:#"myImage.png"];
}];
[operation start];
when you upload image on server first of all save image in document directory with same name each time. in the code image save name is #""Profile1.jpeg"
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
img = [self imageWithImage:img scaledToSize:CGSizeMake(70, 70)];
[btn_Photo setImage:img forState:UIControlStateNormal];
NSData *webData = UIImageJPEGRepresentation(img, 0.5);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.savedImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",#"Profile1.jpeg"]];
[webData writeToFile:self.savedImagePath atomically:YES];
[picker dismissViewControllerAnimated:YES completion:^{
//[[UIApplication sharedApplication] setStatusBarHidden:YES];
}];
}
Using New ANetworking Upload image as below code New AFNetworking
AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
[Manager POST:str_Submit parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
NSURL *filePath_Profile_Logo = [NSURL fileURLWithPath:self.savedImagePath];
[formData appendPartWithFileURL:filePath_Profile_Logo name:#"userfile" error:nil];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Success");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Fail")
}];
please check your document directory path image is change before upload it or not.
please
Related
I've been looking examples for the new AFNetworking 2.0 to upload images. But the pictures I upload always failed. So this is the code I used
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *imagetes = info[UIImagePickerControllerOriginalImage];
self.picprofile.image = imagetes;
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:#[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
NSLog(#"FileName == %#", filename);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"do":#"profile",#"what":#"editFoto",#"session":sesion};
NSString *URLString = BaseURLString;
NSData *imageData = UIImageJPEGRepresentation(self.picprofile.image, 0.5); // image size ca. 50 KB
NSLog(#"imageData == %#", imageData);
[manager.requestSerializer setTimeoutInterval:120];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:#"foto" fileName:filename mimeType:#"image/jpeg"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure %#, %#", error, operation.responseString);
}];
[self dismissViewControllerAnimated:NO completion:nil];
}
I have previously uploaded files to a presigned URL by doing the following:
NSData *data = [NSData dataWithContentsOfURL:self.videoURL];
[self.httpSessionManager.requestSerializer setValue:#"video/mp4" forHTTPHeaderField:#"Content-Type"];
[self.httpSessionManager PUT:operation.relativeURLString parameters:#{#"data": data} success:^(NSURLSessionDataTask *task, id responseObject) {
[self handleResponse:responseObject forSuccessfulOperation:operation];
} failure:^(NSURLSessionDataTask *task, NSError *error) {
[self handleError:error forFailedOperation:operation];
}];
But the need to track uploading progress made me change this into:
NSData *data = [NSData dataWithContentsOfURL:self.videoURL];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"PUT" URLString:operation.relativeURLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data
name:#"data"
fileName:#"video.mp4"
mimeType:#"video/mp4"];
} error:nil];
NSURLSessionDataTask *uploadTask = [self.httpSessionManager uploadTaskWithStreamedRequest:request progress:progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (!error)
{
[self handleResponse:responseObject forSuccessfulOperation:operation];
}
else
{
[self handleError:error forFailedOperation:operation];
}
}];
[uploadTask resume];
This seems to upload the file successfully until I try to play it. It has the correct file size, but the file seems to be broken since it will not play. Am I misinterpreting how to use multipartFormRequest? I have come to understand that using NSStream or a memory mapped file instead of passing along NSData is preferable, but to my knowledge, this shouldn't be the cause of my issue, but a mere performance tweak.
I want to create method in that coming images and all of them downloading in queue one by one. I use AFNetworking 2.0. I want to know is there any pre-created code that can help me in my question ?
My code
NSString *urlString = link;
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
UIImage *image = responseObject;
//here I seve image to disk and so on
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DDLogError(#"FAIL download image: %#",error);
}];
Try with dispatch_group: all downloads are group into one queue and are downloaded one by one
AFNetworking 2.0 download multiple images with completion
I've been looking examples for the new AFNetworking 2.0 to upload images.
But I'm hitting wall and couldn't figure out what's wrong with the code.
So this is the code I used
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://myserverurl.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:imageData progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
TIA
I ended up using the multi-part request
UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFormData:imageData name:#"image"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I want to upload video to web service along with some other parameters. I want to upload userID, videoID and video to web service. While uploading, all the parameters other than video is being sent to web service. I've checked at web service end, and the video is not coming with the request. I am using the following code.
- (void)uploadVideoAtLocalPath:(NSString *)videoPath videoID:(NSString *)videoID userID:(NSString *)userID {
NSString *strServerURL = #"www.mysite.com/user/uploadVideo";
NSURL *URL = [NSURL URLWithString:strServerURL];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:URL];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// userID
NSData *userIDData = [userID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:userIDData name:#"userID"];
// videoID
NSData *videoIDData = [videoID dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:videoIDData name:#"videoID"];
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
[request setURL:URL];
[request setTimeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[AFHTTPRequestOperation addAcceptableStatusCodes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(100, 500)]];
[operation setCompletionBlockWithSuccess: ^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response String: %#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[client enqueueHTTPRequestOperation:operation];
}
Could anyone let me know whether I am doing it correct? If not, could anyone please tell me how to upload video to web service along with other parameters?
Thanks Everyone!
I'm not well in this method. I had the same issue. But, i have fixed it like mixing of POST & GET methods. I just sent my parameters as GET method like below -
NSString *strServerURL = [NSString stringWithFormat:#"www.mysite.com/user/uploadVideo&userID=%d&videoID=%d", 1, 55];
and, sent my video data in POST method as per your method -
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:#"POST" path:#"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
// video
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];
[formData appendPartWithFileData:videoData name:#"video" fileName:#"video.mov" mimeType:#"video/quicktime"];
}];
You better try to modify your webservice and try like above way. It should works.
Cheers!