Is there any way to upload , download to a server read the .sqlite file present in document directory from your iPhone application and use it as your database.
I tried by converting to binary data and uploading but the file is getting encrypted I cannot read or write it after restoring/downloading it from server.
Any suggestion?
Uploading task fetching the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *chatDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ChatDB.sqlite"];
NSString *contactDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ContactDB.sqlite"];
NSURL*ChatDB_url = [NSURL fileURLWithPath:chatDatabasePath];
NSURL*ContactDB_url = [NSURL fileURLWithPath:contactDatabasePath];
self.ChatDBData = [NSData dataWithContentsOfURL:ChatDB_url];
self.ContactDBData = [NSData dataWithContentsOfURL:ContactDB_url];
Uploading
-(void)UploadDbToServer:(NSData*)DB_Data ForDbName:(NSString*)dbName forExtension:(NSString*)extension andCallback:(void (^)(id))callback{
NSString *urlString = [[NSString alloc]initWithString:[NSString stringWithFormat:#"%#chat-backup-upload",baseUrl]];
urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"7MA4YWxkTrZu0gW";
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add DB data
if (DB_Data) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"DB\"; filename=\"%#.%#\"\r\n",dbName,extension] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: file/sqlite\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:DB_Data];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
NSURLSessionConfiguration *sessionConf = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConf];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id jsonResponse= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
callback ((id) jsonResponse);
}];
[task resume];}
Downloading
(void)startDownload:(NSURL*)url {
NSURL *Url= [NSURL URLWithString:[NSString stringWithFormat:#"%#",url]];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue setMaxConcurrentOperationCount:5];
self.activeUrlString=[NSString stringWithFormat:#"%#",Url];
if (!self.session) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:#"image"];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:queue];
}
NSURLRequest* request = [NSURLRequest requestWithURL:Url];
self.task = [self.session downloadTaskWithRequest:request];
[self.task resume];}
Writing the downloaded file
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
//saving the files
NSData *DBData = [NSData dataWithContentsOfURL:location];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *chatDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ChatDB.sqlite"];
NSString *contactDatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ContactDB.sqlite"];
if ([self.activeDownload isEqualToString:#"chat"]){
[DBData writeToFile:chatDatabasePath atomically:YES];
self.activeDownload = #"contact";
[self startDownload:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",pingovaURL,self.ContactDB_URL]]];
}else{
[DBData writeToFile:contactDatabasePath atomically:YES]; }}
Related
I use the following code to upload images to the server:
void call_MediaUploadAPI(NSArray *parameters, NSString *url, BOOL isAnUpdate, SuccessBlock successBlock, FailureBlock failureBlock)
{
NSString *boundary = #"----WebKitFormBoundary7MA4YWxkTrZu0gW";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", BASEURL, url]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:600.0];
[request setHTTPMethod:#"POST"];
NSString *token = [[NSUserDefaults standardUserDefaults]valueForKey:TOKEN];
NSString *authValue = [NSString stringWithFormat: #"JWT %#",token];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
NSError *error;
NSMutableData *body = [NSMutableData data];
for (NSDictionary *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if (param[#"fileName"]) {
NSString *mimetype = [[NetworkIntractor sharedManager] mimeTypeForPath:param[#"fileName"]];
NSData *imageData = [NSData dataWithContentsOfFile:param[#"fileName"]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"; filename=\"%#\"\r\n", param[#"name"], param[#"fileName"]]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Type: %#\r\n\r\n", mimetype]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
if (error) {
NSLog(#"%#", error);
}
} else {
[body appendData:[[NSString stringWithFormat:#"Content-Disposition:form-data; name=\"%#\"\r\n\r\n", param[#"name"]]dataUsingEncoding:NSUTF8StringEncoding]];
if ([param[#"name"] isEqualToString:#"data"]) {
[body appendData:[NSJSONSerialization dataWithJSONObject:param[#"value"] options:0 error:nil] ];
}else{
[body appendData:[[NSString stringWithFormat:#"%#", param[#"value"]]dataUsingEncoding:NSUTF8StringEncoding] ];
}
}
}
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary]dataUsingEncoding:NSUTF8StringEncoding] ];
[request setHTTPBody:body];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if (dict != nil) {
NSLog(#"multipart api response : %#", dict);
successBlock(dict,response);
}else
{
NSLog(#"multipart api failure response : %#", error);
failureBlock(error,response);
}
}}];
[task resume];
}
I tried giving different combination of timeout intervals like this:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.timeoutIntervalForRequest = 150.0f;
config.timeoutIntervalForResource = 300.0f;
self.session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
But, for a bit larger image files, I never get response back from the server though the image gets uploaded as I can find them available in the admin panel.
FIRST ERROR
I use this code but I don't know how to use the api Mailjet in iOS ? Where to put the API key private, the public etc...
I check the github mailjet, the doc mailJet about the API without success.
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSLog(#"File Size: %lu",(unsigned long)[data length]);
//set up request
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://api.mailjet.com/v3/send"]];
[request setHTTPMethod:#"POST"];
//required xtra info
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//body of the post
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"thefile\"; filename=\"recording\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[#"Content-Type: application/octet-stream\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSURLConnection *apiConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I do tests with sending "manually", and I have that bad answer. Where I have to put the API KEY and the SECRET KEY ?
EDIT
SECOND ERROR
New code :
NSString *apiKey = #"*******************";
NSString *secretKey = #"**************";
NSString *mail = #"******#******.***";
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"1.0" forKey:#"ver"];
[_params setObject:#"en" forKey:#"lan"];
[_params setObject:apiKey forKey:#"apiKey"];
[_params setObject:secretKey forKey:#"secretKey"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------***********";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"file";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"https://api.mailjet.com/v3/send/"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", apiKey, secretKey];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64Encoding];
[request setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"#"application/json"; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
[request addValue:apiKey forHTTPHeaderField:#"apiKey"] ;
[request addValue:secretKey forHTTPHeaderField:#"secretKey"] ;
// post bodyv
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; FromEmail:\"contact#****.fr\"; \"Text-part\":\"Dear\" ; Recipients:[{\"Email\":\"****#gmail.com\"}]; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#, error: %#", requestReply, error);
}] resume];
New error message:
Any ideas?
Here is the code:
- (void) sendToMail:(NSString *)mailingList
{
NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:STATS_FILE];
NSFileManager *fileManager = [NSFileManager defaultManager];
mailingList = MAILING_LIST;
if ([fileManager fileExistsAtPath:filePath])
{
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"xxxx#xxxx.xxx" forKey:#"FromEmail"];
[_params setObject:#"xxx xxx xxxx" forKey:#"FromName"];
[_params setObject:#"xxx xxx xxx" forKey:#"Subject"];
[_params setObject:#"xxx xxxx xxxx" forKey:#"Html-part"];
//mail(s) treatment
NSUInteger numberOfOccurrences = [[mailingList componentsSeparatedByString:#";"] count] - 1;
NSArray *subStrings = [mailingList componentsSeparatedByString:#";"];
NSMutableArray *mailsArr = [NSMutableArray new];
for (int i=0; i<=numberOfOccurrences; i++)
{
NSString *mail = [subStrings objectAtIndex:i];
if ([self validEmail:mail])
[mailsArr addObject:#{#"Email":mail}];
}
if ([mailsArr count] > 0)
[_params setObject:mailsArr forKey:#"Recipients"];
//add any attachment file to JSON
NSData* data = [NSData dataWithContentsOfFile:filePath];
if (data)
{
NSString *encodedString = [data base64EncodedStringWithOptions:0];
NSArray *attachmentsArr = #[#{#"Content-type":#"text/plain", #"Filename":[NSString stringWithFormat:#"%#.db", [[[UIDevice currentDevice] identifierForVendor] UUIDString]], #"content":encodedString}];
[_params setObject:attachmentsArr forKey:#"Attachments"];
}
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"https://api.mailjet.com/v3/send/"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:#"%#:%#", API_KEY, SECRET_KEY];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64EncodedStringWithOptions:0];
[request setValue:[NSString stringWithFormat:#"Basic %#", authenticationValue] forHTTPHeaderField:#"Authorization"];
NSString *jsonRequest = [_params JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSMutableData *requestData = [[jsonRequest dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// setting the body of the post to the request
[request setHTTPBody:requestData];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL]; // set URL
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
#if DEBUG
NSLog(#"requestReply: %#, error: %#", requestReply, error);
#endif
if (error == nil)
{
[self showAlertWithMessage:#"File sent!" withButton:#"Ok!"];
}
else
{
[self showAlertWithMessage:#"Could not send file!" withButton:#"Ok!"];
}
}] resume];
}
I'm leading the API at Mailjet.
Few things to note in your post:
It seems your call lacks a Basic Authentification, see Postman documentation for more details on about to set it. You can fetch your API credentials here
You use a form-data Content-Type while our API only supports application/json as input format. Please refer to our API guides for more details about the payload to send us
You do not seem to provide your API credentials in the objective-c code you provided. Same than in the first point, you can fetch them from here
We do not officially support iOS with Objective-C or Swift, apologies for the inconvenience.
Hope it helps
Thanks for having chosen Mailjet to power your emails!
I can't upload images to Cloudinary hosting via HTTPS POST request, I want to use the simple API methods instead of the SDK. I'm having a problem with formatting the image in a byte array buffer or as Base64 encoded.
Here's my code:
UIImage *image = [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *strImageData = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSURL *url = [NSURL URLWithString:#"https://api.cloudinary.com/v1_1/MYSECTER/image/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
NSString *strRequest = [NSString stringWithFormat:#"file=%#&upload_preset=MYSECTER", strImageData];
request.HTTPBody = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"RECEIVED: %#", recievedData);
}] resume];
Unfortunately I receive the following answer from the server: "Unsupported source URL..."
I really tried a lot of other methods, but I can't get it to work.
UPDATE: When I put URL link at 'file' param all works fine.
I don't have any experience with the Cloudinary API but I hope this is helpful. I had a look at the docs on 'Uploading with a direct call to the API'.
I think you are required to provide the 'file' and 'upload_preset' as POST parameters (not concatenated as data in the body).
UIImage *image = [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(image);
NSString *strImageData = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSURL *url = [NSURL URLWithString:#"https://api.cloudinary.com/v1_1/MYSECTER/image/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
// Replace this:
//NSString *strRequest = [NSString stringWithFormat:#"file=%#&upload_preset=MYSECTER", strImageData];
//request.HTTPBody = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
// With this:
NSString *imageDataStr = [[NSString alloc] initWithData:imageData encoding:NSUTF8StringEncoding];
[request setValue:imageDataStr forHTTPHeaderField:#"file"];
[request setValue:#"MYSECTER" forHTTPHeaderField:#"upload_preset"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"RECEIVED: %#", recievedData);
}] resume];
You can use Cloudinary's SDK in order to perform an upload image task as explained here: http://cloudinary.com/blog/direct_upload_made_easy_from_browser_or_mobile_app_to_the_cloud
The following code samples show a direct unsigned upload API call in Objective-C for iOS...:
CLCloudinary *cloudinary = [[CLCloudinary alloc] init];
[cloudinary.config setValue:#"demo" forKey:#"cloud_name"];
NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:#"logo"
ofType:#"png"];
CLUploader* uploader = [[CLUploader alloc] init:cloudinary delegate:self];
[uploader unsignedUpload:imageFilePath uploadPreset:#"zcudy0uz" options:#{}];
The following code samples show a more advanced example: specifying a custom public ID of user_sample_image_1002, making it possible to later access the uploaded image, and assigning a tag to simplify management of the images. In addition, we show an example of building a dynamic URL that performs an on-the-fly image manipulation: generating a 150x100 face-detection-based thumbnail of the uploaded images for embedding in your application.
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
[uploader unsignedUpload:imageData uploadPreset:#"zcudy0uz" options:
[NSDictionary dictionaryWithObjectsAndKeys:#"user_sample_image_1002",
#"public_id", #"tags", #"ios_upload", nil] withCompletion:^(NSDictionary
*successResult, NSString *errorResult, NSInteger code, id context) {
if (successResult) {
NSString* publicId = [successResult valueForKey:#"public_id"];
NSLog(#"Upload success. Public ID=%#, Full result=%#", publicId,
successResult);
CLTransformation *transformation = [CLTransformation transformation];
[transformation setWidthWithInt: 150];
[transformation setHeightWithInt: 100];
[transformation setCrop: #"fill"];
[transformation setGravity:#"face"];
NSLog(#"Result: %#", [cloudinary url:publicId
options:#{#"transformation":
transformation, #"format": #"jpg"}]);
} else {
NSLog(#"Upload error: %#, %d", errorResult, code);
}
} andProgress:^(NSInteger bytesWritten, NSInteger totalBytesWritten,
NSInteger totalBytesExpectedToWrite, id context) {
NSLog(#"Upload progress: %d/%d (+%d)", totalBytesWritten,
totalBytesExpectedToWrite, bytesWritten);
}];
I found solution, and it works very good:
// image for sending
UIImage *image = [UIImage imageNamed:#"image.png"];
// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:#"SECKET_PRESET" forKey:#"upload_preset"];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"file";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#"https://api.cloudinary.com/v1_1/SECKET_KEY/image/upload"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in _params) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
// add image data
NSData *imageData = UIImagePNGRepresentation(image);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *recievedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"RECEIVED: %#", recievedData);
}] resume];
i am developeing share extension for my iOS application. i had really done every thing but the problem is that my code is only working for small images but when i upload image taken from device camer then uploading fails and only text get uploded.
- (void)performUploadWith:(NSDictionary *)parameters imageFile:(UIImage *)image{
NSString *boundary = #"SportuondoFormBoundary";
// NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];
// NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
// NSMutableURLRequest *request;//[NSURLRequest pho]
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{
#"api-key" : #"55e76dc4bbae25b066cb",
#"Accept" : #"application/json",
#"Content-Type" : [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary]
};
NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSMutableData *body = [NSMutableData data];
for (NSString *key in parameters)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"imageDATE, %#", imageData);
if (imageData)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", #"file"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",kURLBase,kURLAddPostDL]];
NSLog(#"url %#",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10000];
request.HTTPMethod = #"POST";
request.HTTPBody = body;
NSURLSessionUploadTask *upload=[session uploadTaskWithRequest:request fromData:request.HTTPBody];
[upload resume];
}
i update my code to this and i check on server my request never reaches to server. I am using this code
NSInteger randomNumber = arc4random() % 1000000;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:#"testSession.foo.%d", randomNumber]];
config.sharedContainerIdentifier=kGroupNameToShareData;
session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:[NSString stringWithFormat:#"file://%#", dataSrcImagePath]]];
[uploadTask resume];
Extensions aren't allowed their own cache disk space. Need to share with application
Uploading large image need cache disk space,so you upload failed.
You need create url session with following codes:
let configName = "com.shinobicontrols.ShareAlike.BackgroundSessionConfig"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configName)
// Extensions aren't allowed their own cache disk space. Need to share with application
sessionConfig.sharedContainerIdentifier = "group.ShareAlike"
let session = NSURLSession(configuration: sessionConfig)
and then setting the app group both extension target and containing app.
and more infomations you can refer following link:
http://www.shinobicontrols.com/blog/posts/2014/07/21/ios8-day-by-day-day-2-sharing-extension
You should be using a background NSURLSession since you are meant to dismiss the sharing UI as soon as possible by calling completeRequestByReturningItems on your NSExtensionContext instance.
The problem is i am not using background session
NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];
- (void)performUploadWith3:(NSDictionary *)parameters imageFile:(UIImage *)image
{
NSString *fileName = #"image.file";
NSString *boundary= #"Boundary+2EB36F87257DBBD4";
NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:kGroupNameToShareData];
storeURL=[storeURL URLByAppendingPathComponent:fileName];
NSLog(#"sotre url %#",storeURL);
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
imageData =[self appendParams:parameters andImage:image bondary:boundary];
if (!([imageData writeToFile:[storeURL path] atomically:YES]))
{
NSLog(#"Failed to save file.");
}
NSString *string=#"URL here";
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
for (NSString *key in parameters)
{
[request setValue:[parameters objectForKey:key] forHTTPHeaderField:key];
}
if (session == nil)
{
//If this is the first upload in this batch, set up a new session
//Each background session needs a unique ID, so get a random number
NSInteger randomNumber = arc4random() % 1000000;
sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:#"and unique name"]];
sessionConfiguration.sharedContainerIdentifier=kGroupNameToShareData;
// config.HTTPMaximumConnectionsPerHost = 1;
session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
//Set the session ID in the sending message structure so we can retrieve it from the
//delegate methods later
// [sendingMessage setValue:session.configuration.identifier forKey:#"sessionId"];
NSLog(#"config %#",sessionConfiguration.sharedContainerIdentifier);
}
if([[NSFileManager defaultManager]fileExistsAtPath:[storeURL path]])
{
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:storeURL];
[uploadTask resume];
}
else
NSLog(#"file does not exsit");
NSLog(#"desc %#",[session sessionDescription]);
// NSLog(#"state %ld", [uploadTask state]);
}
HELP please..
I'm trying to upload .txt file to web service.. any idea please?
here how i used to send data to web service
self.responseData=[[NSMutableData alloc]initWithLength:0];
NSString *tempString=[[NSString alloc]initWithFormat:#"%#",Register_URL];
NSURL *url = [NSURL URLWithString:[tempString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
(void)[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
Just found solution .. hope it will help any one :)
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:yourFileName.txt];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath: fullFilePath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"yourServiceURL"]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"userfile\"; filename=\"yourFileName.txt\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
dispatch_async(dispatch_get_main_queue(),^ {
[self LogResult:returnString];
});
});
somewhere in your class implement "LogResult:" method .