I have implemented
-(void)uploadMultipleImagesUsingAFNetworkingMultipartFormat:(id)sender {
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[FileUtility basePath] stringByAppendingPathComponent:[self getPathOfRootImageFolderDocumentId:#"1"]] error:nil];
NSString *path = [directoryContents objectAtIndex:0];
NSString* filePath=[[[FileUtility basePath] stringByAppendingPathComponent:[self getPathOfRootImageFolderDocumentId:#"1"]] stringByAppendingPathComponent:path];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:#"com.uploadDocument.Background"];
MBProgressHUD *progres = [MBProgressHUD showHUDAddedTo:[[AppDelegate sharedInstance] window] animated:YES];
progres.mode = MBProgressHUDModeDeterminateHorizontalBar;
progres.progress = 0.0;
if (!self.sessionManager) {
_sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
}
NSError *error;
NSMutableURLRequest *requet= [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"URLTO UPLOAD" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSError *error1;
[formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:#"fileUpload" fileName:path mimeType:#"image/jpeg" error:&error1];
NSLog(#"%#",error1);
} error:&error];
NSURLSessionUploadTask *uploadTask = [self.sessionManager uploadTaskWithRequest:requet fromFile:[NSURL fileURLWithPath:filePath] progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
[progres setProgress:uploadProgress.fractionCompleted];
});
NSLog(#" Progress %f",uploadProgress.fractionCompleted);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:[AppDelegate sharedInstance].window animated:YES];
});
}];
[uploadTask resume];
}
But when i put it in background, and set active after some time. i observe that process start from where is paused.
How to continue upload task in background too?
plz on background fetch in background modes then try :)
You just need to add below code as there is bug in NSURLSessionTask for background task.
// Prepare a temporary file to store the multipart request prior to sending it to the server due to an alleged
// bug in NSURLSessionTask.
NSString* tmpFilename = [NSString stringWithFormat:#"%f", [NSDate timeIntervalSinceReferenceDate]];
NSURL* tmpFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tmpFilename]];
// Dump multipart request into the temporary file.
[[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:requet
writingStreamContentsToFile:tmpFileUrl
completionHandler:^(NSError *error)
{
// Once the multipart form is serialized into a temporary file, we can initialize
// the actual HTTP request using session manager.
// Here note that we are submitting the initial multipart request. We are, however,
// forcing the body stream to be read from the temporary file.
NSURLSessionUploadTask *uploadTask = [self.sessionManager uploadTaskWithRequest:requet fromFile:tmpFileUrl progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
[progres setProgress:uploadProgress.fractionCompleted];
});
NSLog(#" Progress %f",uploadProgress.fractionCompleted);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:[AppDelegate sharedInstance].window animated:YES];
});
}];
[uploadTask resume];
}];
Hope this will help you. And if you have any question then please ask.
Related
I'm using AFNetworking 3.0 and I try to send files to my server, my code work perfectly but it's very long to send the file especially when I try to send a video.
I compress the video quality and it's a little bit fast but to send a 5 sec video that take 15-20 sec.
I want to know if it's possible to improve the speed to send the file.
There is my code :
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"urlOfServer" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:videoData name:#"fileName" fileName:#"filename.mp4" mimeType:#"video/mp4"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
NSLog(#"PERCENTAGE UPLOADED %f",uploadProgress.fractionCompleted);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
Thank for your help
Since you only write to the debug console to report the progress and you don't change any UI elements, the dispatch_get_main_queue is not needed. Try to remove it and see if it makes a difference in performance.
i am using plist to save my data locally when network connection is not available, and when network is available i want to sync my locally saved data to the web server.
i am using this code. but i don't know whether the data is saved in server or not.
(IBAction)manualSync:(id)sender {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example_url"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://plist_name"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
}
i am assigning my api to the URL in which i want to save the data of plist, and my plist to the file path in which my data is already saved. can anyone solve this issue.
I think you use normal API Call to stored pList file to a server. Becuase when you read plist file, your will data in NSDictionary and you send it server to store.
To send plist values into server:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *strWebService = [NSString stringWithFormat:#"YOUR_BASE_URL"];
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"YOUR_PLIST_NAME" ofType:#"plist"];
NSDictionary *dicData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
[manager POST:strWebService parameters:dicData constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
} progress:^(NSProgress * _Nonnull uploadProgress)
{
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"%#",responseObject)
;
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
I'm new to ios.
How to send an image or an video to php server. i have a key "Image"
for sending image and key "Video" to send video file. i need to send image or video with their keys, how can i send...?
Use Post method. And you should archive image/video to data and make sheet data to send it to server.
I suggest you use Alamofire to do this. This is the code.
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in
debugPrint(response)
}
Here is the link.
Update
As you're familiar with OC, use AFNetworking instead. This is the code.
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
Here is the link.
Im trying to upload image to my server by using AFNetworking 3.0. My server returns "Please select a file to upload.". Here is how i catch the uploaded file in my php file $filename = $_FILES["file"]["name"];.
-(void)uplodeImages :(NSString *)image {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://local/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:image] name:#"file" fileName:#"imagename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Laddar...");
});
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
}
Note :- I have just implemented Image Upload service using AFNetworking 3.0,
-> Here kBaseURL means Base URL of server
->serviceName means Name of Service.
->dictParams means give parameters if needed, otherwise nil.
->image means pass your image.
Note :- This code written in NSObject Class and we have apply in our Project.
+ (void)requestPostUrlWithImage: (NSString *)serviceName parameters:(NSDictionary *)dictParams image:(UIImage *)image success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[SVProgressHUD show];
NSData *fileData = image?UIImageJPEGRepresentation(image, 0.5):nil;
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:strService parameters:dictParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(fileData){
[formData appendPartWithFileData:fileData
name:#"image"
fileName:#"img.jpeg"
mimeType:#"multipart/form-data"];
}
} error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Wrote %f", uploadProgress.fractionCompleted);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
[SVProgressHUD dismiss];
if (error)
{
failure(error);
}
else
{
NSLog(#"POST Response : %#",responseObject);
success(responseObject);
}
}];
[uploadTask resume];
}
--> Now apply in our project.
UIImage *imgProfile = //Pass your image.
[WebService requestPostUrlWithImage:#"save-family-member" parameters:nil image:imgProfile success:^(NSDictionary *responce) {
NSString *check = [NSString stringWithFormat:#"%#",[responce objectForKey:#"status"]];
if ([check isEqualToString: #"1"]) {
//Image Uploaded.
}
else
{
//Failed to Upload.
}
} failure:^(NSError *error) {
//Error
}];
My iOS app is crashing when my video upload is in process and app enters to background even it did not call didEnterbackground method.
Do anybody have an idea what causing it and how do I manage that uploading even if my app is in background.
Did you try background session? Like this:
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.you.uoload")
let session = NSURLSession(configuration: configuration, delegate: nil, delegateQueue: NSOperationQueue.mainQueue())
You should use NSURLSessionUploadTask to make asynchronous upload request.
Your request may be synchronous and thats why it is producing error i think.
Using AFNetworking you can do something like,
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:#"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:#"file://path/to/image.jpg"] name:#"file" fileName:#"filename.jpg" mimeType:#"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"%# %#", response, responseObject);
}
}];
[uploadTask resume];
You can refer this answer for more details.
Hope this will help :)