How to send Text and Images to server using NSURLConnection in ios - ios

Hi i am very beginner in Ios and in my project i need to send "Username" and "Password" and "UserImage" to server using NSURLConnection and for this i have inserted this three fields(username,password,userimage) in one Dictionary and i am posting this dictionary to server but using my below code details are not sending to server please help me what did i do here wrong
my code:-
#interface SendingImagesToServer ()
{
NSMutableData *body;
}
#end
#implementation SendingImagesToServer
- (void)viewDidLoad {
[super viewDidLoad];
NSData *imageData;
UIImage * image;
NSError *error = nil;
image = [UIImage imageNamed:#"friendship.jpg"];
imageData = UIImageJPEGRepresentation(image, 0.1f);
NSDictionary *mainDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"James" ,#"username",
#"1234",#"Password",
imageData,#"image",
nil];
NSString *jsonString = [mainDict JSONRepresentation];
NSData * webbody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
body = [webbody mutableCopy];
NSString *urlstr = [NSString stringWithFormat:#"My url here"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Disposition: form-data; name=\"imagename\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
if(imageData == nil && error!=nil) {
NSLog(#"nil");
}
else
{
NSLog(#"not nill");
}
[body appendData:[#"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Successfully sending to server");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"error is %#",[error localizedDescription]);
}
#end

You create the request, but don't start it anywhere in your code. Also you don't create the NSURLConnection anywhere (at least not in the posted part).
The easiest way to achieve this would be to simply add this line at the end of your viewDidLoad method :
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You can read more here

Related

How can I send an email with attachement using the API MailJet in iOS programmatically?

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!

How to upload video with Privacy setting unlisted in Youtube

I am uploading video on youtube using this code..
- (void)sendVideoFileMetadata:(NSDictionary *)videoMetadata
error:(NSError **)error
{
[self logDebug:#"Sending file info..."];
NSString *category = videoMetadata[kDDYouTubeVideoMetadataCategoryKey];
NSString *keywords = videoMetadata[kDDYouTubeVideoMetadataKeywordsKey];
NSString *title = videoMetadata[kDDYouTubeVideoMetadataTitleKey];
NSString *desc = videoMetadata[kDDYouTubeVideoMetadataDescriptionKey];
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"<media:privacyStatus>unlisted</media:privacyStatus>"
#"</media:group>"
#"</entry>", title, desc, category, keywords];
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/action/GetUploadToken"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"GoogleLogin auth=\"%#\"", self.authorizationToken] forHTTPHeaderField:#"Authorization"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:#"unlisted" forHTTPHeaderField:#"privacyStatus"];
[request setValue:[NSString stringWithFormat:#"key=%#", self.developerKey] forHTTPHeaderField:#"X-GData-Key"];
[request setValue:#"application/atom+xml; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%u", (unsigned int)xml.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]];
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypePrepare];
// Create error if there were
// problems creating a connection
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
}
}
- (BOOL)uploadVideoFile:(NSURL *)fileURL
error:(NSError **)error
{
NSString *boundary = #"AbyRvAlG";
NSString *nextURL = #"http://www.youtube.com";
NSData *fileData = [NSData dataWithContentsOfFile:[fileURL relativePath]];
_videoFileLength = [fileData length];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#?nexturl=%#", self.uploadURLString, nextURL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary] forHTTPHeaderField:#"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSMutableString *bodyString = [NSMutableString new];
// Add token
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendString:#"Content-Disposition: form-data; name=\"token\"\r\n"];
[bodyString appendString:#"Content-Type: text/plain\r\n\r\n"];
[bodyString appendFormat:#"%#", self.uploadToken];
// Add file name
[bodyString appendFormat:#"\r\n--%#\r\n", boundary];
[bodyString appendFormat:#"Content-Disposition: form-data; name=\"file\"; filename=\"%#\"\r\n", [fileURL lastPathComponent]];
[bodyString appendFormat:#"Content-Type: application/octet-stream\r\n\r\n"];
[bodyString appendFormat:#"privacyStatus: unlisted\r\n\r\n"];
// Create the data
[body appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Set the body
[request setHTTPBody:body];
// Create the connection
self.responseData = [[NSMutableData alloc] init];
self.currentConnection = [DDURLConnection connectionWithRequest:request delegate:self];
[self.currentConnection setType:DDYouTubeUploaderConnectionTypeUpload];
if (!self.currentConnection)
{
*error = [self createErrorWithCode:DDYouTubeUploaderErrorCodeCannotCreateConnection
description:#"Cannot create connection to YouTube."];
return NO;
}
return YES;
}
This working perfectly,
But the issue is video uploaded as Public, i want to upload it as Unlisted.
I have tried so many tag but not able to get success.
Used,
- privacy
- privacystatus
Can anyone let me know where should i add the tag and whats the tag?
Code snippet will be more helpful.
Just update xml by adding
<yt.accesscontrol>
and it will uplaoad video as unlisted
NSString *xml = [NSString stringWithFormat:
#"<?xml version=\"1.0\"?>"
#"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
#"<media:group>"
#"<media:title type=\"plain\">%#</media:title>"
#"<media:description type=\"plain\">%#</media:description>"
#"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%#</media:category>"
#"<media:keywords>%#</media:keywords>"
#"</media:group>"
#"<yt:accessControl action='list' permission='denied'/>"
#"</entry>", title, desc, category, keywords];

how to upload multiple images to server ios?

I am trying to upload Image From my IOS device to server. when upload single image file to server it is successfully uploaded to my server. i want to upload multiple image files to server how can i do this.
// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:#"icon.png"], 1.0f);
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
NSString *filename = #"icon";
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
Muliple images upload attempted code
-(void)uploadImageToServer:(NSArray*)arrUploadData withTreatmentDetails:(NSDictionary *)dictArguments url:(NSString*)url
{
// COnvert Image to NSData
// set your URL Where to Upload Image
NSString *urlString = #"http://XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/imgupload.php";
// set your Image Name
// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
for (int i=0; i<[arrUploadData count]; i++)
{
NSData *dataImage = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyData"];
NSString *filename = [[arrUploadData objectAtIndex:i] valueForKey:#"photographyimagename"];
if (dataImage)
{
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.png\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[#"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",responseString);
}
Hello, You can do it by using NSMutableArray
For Example :
NSMutableArray *arrayImageData = [[NSMutableArray alloc]init];
Take images from imagepicker
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissViewControllerAnimated:YES completion:nil];
NSString *filePath,*path;
NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:#"UIImagePickerControllerOriginalImage"],1);
[arrayImageData addObject:dataImage];
filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"screenShot1.png"];
[picker dismissViewControllerAnimated:YES completion:nil];
}
At the time of posting image on Server use following code
for (int i = 0; i < [arrayImageData count]; i++)
{
[request setPostValue:[[MYUtility getInstance] base64StringFromNSData:[arrayImageData objectAtIndex:i]] forKey:[NSString stringWithFormat:#"Image%d", i + 1]];
}
Hope this will help for you...I used this code for saving multiple images on server.

Migrating from NSURLConnection to NSURLSession

I am trying to migrate to NSURLSession so I can send multiple images to my server and stop when I get the needed response. But my completion block never gets called. Would appreciate if you could tell me if I am doing the migration correctly.
Here is my old code that works fine-
-(void) sendImgWithText:(UIImage*)img
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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 params (all params are strings)
// UIImage *imgColor = [UIImage imageNamed:#"9.jpg"];
UIImage * imageToPost = [[UIImage alloc] init];
UIImageWriteToSavedPhotosAlbum(imageToPost, nil, nil, nil);
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
And here is the version(I got most of it from other stack overflow articles)
- (void) serverRequestWithImage:(UIImage *)img completion:(void (^)(id responseObject, NSError *error))completion
{
NSURL *requestURL = [NSURL URLWithString:#"Some URL"];
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"*****";
NSString *lineEnd = #"\r\n";
NSString *twoHyphens = #"--";
// 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];
UIImage * imageToPost = [[UIImage alloc] init];
imageToPost = img;
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
[body appendData:[[NSString stringWithFormat:#"%#%#%#", twoHyphens,boundary, lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// [body appendData:[#"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:#"%#",lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:#"%#%#%#%#", twoHyphens,boundary, twoHyphens,lineEnd] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
NSLog(#"%#",requestURL);
NSLog(#"%f,%f",imageToPost.size.height,imageToPost.size.height);
// set URL
[request setURL:requestURL];
NSURLSessionTask *task =
[session
dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// report any network-related errors
NSLog(#"Got Response 1");
if (!data) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, error);
});
}
return;
}
// report any errors parsing the JSON
NSError *parseError = nil;
_responseData = [NSMutableData dataWithData:data];
if (_responseData) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil, parseError);
});
}
return;
}
// if everything is ok, then just return the JSON object
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(_returnedData, nil);
});
}
}];
[task resume];
}
And here is my call method from the other class
- (IBAction)GetData:(id)sender
{
[_imageView setImage:[UIImage imageNamed:#"9.jpg"]];
msg = [[Message alloc] init];
[msg initData];
msg.delegate=self;
[msg serverRequestWithImage:_imageView.image completion:^(id responseObject, NSError *error)
{
if (responseObject) {
// do what you want with the response object here
NSLog(#"Got Data");
} else {
NSLog(#"%s: serverRequest error: %#", __FUNCTION__, error);
}
}];
}
Items:
I didn't see the initialization of NSURLSession. That's something you should show in your question. You could also check in your "send image" method that session is non-nil.
It looks like you are starting with a file (#"9.jpg"). If so, -[NSURLSession uploadTaskWithRequest:fromFile:completionHandler:] might save you a bunch of trouble.
Unrequested advice, with all that entails: :)
In my view, -serverRequestWithImage:completion: is a poor name for that method. It implies that it returns a request object, and does not tell you that it actually sends the request. Something active, like -uploadImage:completionHandler: might be better.
Idiomatically, all method names should start lowercase, i.e. -getData:.

How to send request with XML

I want to send XML file to http://api.online-convert.com/queue-insert
I'm using such code:
NSString *urlString = [NSString stringWithFormat:#"http://api.online-convert.com/queue-insert"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:#"text/xml"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"<queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<apiKey>32423sda..2134</apiKey>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<targetType>audio</targetType>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<targetMethod>convert-to-flac</targetMethod>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<testMode>true</testMode>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"</queue>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
}
But I always get error:
<queue-answer>
<status>
<code>8</code>
<message>The XML file is empty</message>
</status>
</queue-answer>
Where is my fault? Please help..
I'm sending XML-file in the following way:
NSString *message = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
url = [NSURL URLWithString:#"https://site.ru/request"];
request = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d",[message length]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
LOG([NSString stringWithFormat:#"Post message: %#"], message);
[message release];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
You probably do not know what you're doing. In the string:
[postBody appendData:[[NSString stringWithFormat:#"<sourceUrl>http://www.online-convert.com/audio/audio-converter.flac</sourceUrl>"] dataUsingEncoding:NSUTF8StringEncoding]];
You are supposed to send the URL to the server where your original file (the file you wish to convert) is located. The link in your code leads to non-existing file.
This piece of code works for me:
- (IBAction)startSOAP:(id)sender
{
NSLog(#"\n{AppDelegate} startSOAP start");
// create the request
NSError **myError;
NSHTTPURLResponse **serverResponse;
NSData *serverData;
NSDictionary *headerFieldsDict = [NSDictionary
dictionaryWithObjectsAndKeys:#"Apple iPhone",#"User- Agent",
#"text/xml; charset=utf-8", #"Content-Type",
#"soapAction",#"SOAP_ACTION",nil];
#try {
// 1) The Request String.
// Note: smsXMLString contains the entire SMS SOAP envelope, without the <? XML declaration command >.
NSString *smsXMLPath = [[NSBundle mainBundle] pathForResource:#"sms" ofType:#"xml"];
self.smsXMLString = [NSString stringWithContentsOfFile:smsXMLPath encoding:NSUTF8StringEncoding error:myError];
// -----------------------
// 2) Create the request.
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theServerURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
// -----------------------
// 2a) Modify the Request from default 'GET' to 'POST':
[theRequest setHTTPMethod:#"POST"];
// 2b) Modify the Headers:
[theRequest setAllHTTPHeaderFields:headerFieldsDict];
// 2c) Sent the Contents of the Body to the SOAP/XML data:
[theRequest setHTTPBody:[self.smsXMLString dataUsingEncoding:NSUTF8StringEncoding]];
// -----------------------
// 3) Get Synchronous Data:
serverData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:serverResponse
error:myError];
// -----------------------
// 4) Convert Synchronous Data into Human-Readable String (Unicode 8) format:
NSString *serverDataString = [[[NSString alloc] initWithData:serverData encoding:NSUTF8StringEncoding] retain];
[[soapResponse layoutManager]replaceTextStorage:[[NSTextStorage alloc] initWithString:serverDataString]];
[serverDataString release];
}
#catch (id e) {
NSLog(#"\n**** {startSOAP} EXCEPTION: %# ****\n",e);
self.statusLine.stringValue = [NSString stringWithFormat:#"*** Exception flagged: %# ***",e];
}
#finally {
NSLog(#"\n{startSoap} end.");
}
}

Resources