Uploading image to server Detail Explanation for Beginner - ios

I'm working on uploading an image to a server from last two days as there are tons of questions about uploading an image through AFNetworking and NSURLSession and other methods of uploading all I'm asking is I didn't found a single answer explaining the whole concept about how the things work and what is going on under the hood I searched youtube also all the stuff are available in Swift and trust me no Explanation at all and from my result I found this answer is something that looks familiar to me
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:#"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = #"api_key=APIKEY&email=example#example.com&password=password";
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
}];
[dataTask resume];
and also the most popular answer about this topic is by User XJones is:-
Here's code from my app to post an image to our web server:
// 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:[NSString stringWithString:#"1.0"] forKey:[NSString stringWithString:#"ver"]];
[_params setObject:[NSString stringWithString:#"en"] forKey:[NSString stringWithString:#"lan"]];
[_params setObject:[NSString stringWithFormat:#"%d", userId] forKey:[NSString stringWithString:#"userId"]];
[_params setObject:[NSString stringWithFormat:#"%#",title] forKey:[NSString stringWithString:#"title"]];
// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:#"----------V2ymHFg03ehbqgZCaKO6jy"];
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = [NSString stringWithString:#"file"];
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:#""];
// 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 = UIImageJPEGRepresentation(imageToPost, 1.0);
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:[[NSString stringWithString:#"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:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];
But my point is I'm learning on my own and it is very difficult to understand for the beginner without explanation so All I'm asking is an explanation, an Detail explanation about the whole process if someone have a hard time to spend on this question because believe it or not I found this the hardest topic till now because the main reason is there are no tutorials about the whole process and also no explanation at all for beginners if someone can a step now and explain the concept it'll be easier to the students who will learn tomorrow. So anybody who can explain this in detail and how the uploading process works and some steps for the reference will be greatly appreciated.
Note : Consider I Have an API and a Key "image" .

here we gonna look at image uploading along with some **parameters because most of time we upload image along with some parameters such as userId.
Before going deep into our topic let me provide the code for doing the stuff source,All the details we gonna see below are from some other stack overflow threads and some from other sites,i'll provide all the links for your reference.
-(void)callApiWithParameters:(NSDictionary *)inputParameter images:(NSArray *)image imageParamters:(NSArray *)FileParamConstant{
//1
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:#"POST"];
//2
NSString *boundary = #"------CLABoundaryGOKUL";
//3
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#", boundary];
[request setValue:contentType forHTTPHeaderField: #"Content-Type"];
//4
NSMutableData *body = [NSMutableData data];
for (NSString *key in inputParameter) {
[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", [inputParameter objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
for (int i = 0; i < image.count; i++) {
NSData *imageDatasss = UIImagePNGRepresentation(image[i]);
if (imageDatasss)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"image.jpg\"\r\n", FileParamConstant[i]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageDatasss];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//5
[request setHTTPBody:body];
//6
[request setURL:[NSURL URLWithString:#"http://changeThisWithYourbaseURL?"]];//Eg:#"http://dev1.com/PTA_dev/webservice/webservice.php?"
//7
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
//8
if ([httpResponse statusCode] == 200) {
NSDictionary * APIResult =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"Response of %#: %#",[inputParameter valueForKey:#"service"],APIResult);
}else{
//9
NSLog(#"%#",error.localizedDescription);
}
}];
}
NOTE: Since it is a broad topic i have provided documentation link for detail info.
We are using ** NSMutableURLRequest** instead of ** NSURLRequest** because we gonna append some data to it.if you need some deep clarification about mutable url request go through this documentation.
setHTTPShouldHandleCookies here we have to decide whether we are going to use cookies or not.To know more about visit
setTimeoutInterval this helps to set a time limit to url request.Add time interval in seconds after the given time,request will be terminated.
setHTTPMethod there are many methods.But we use GET and POST methods in many cases.Difference between POST and GET is here and here
Boundary helps in separating the parameters from each other,so that the server can identify them.The boundary may be anything as your wish feel free to edit it.
Here we use multipart/form-data; boundary= as content type.To know why we are going to this content type look into this thread.
NSMutableData * body we gonna append all the parameters and values to this data and later setHTTPBody to the UrlRequest.
If this is how we call the 'callApiWithParameters' method
- (IBAction)Done:(id)sender{
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],[UIImage imageNamed:#"Test1"],nil];
NSArray * imageParameters = [NSArray arrayWithObjects:#"img_one",#"img_two",nil];
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
then the data (i.e body) will look like this
Content-Type=multipart/form-data; boundary=------CLABoundaryGOKUL
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=user_id
1
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=name
XXX
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_one; filename=image.jpg
Content-Type:image/jpeg
//First image data appended here
--------CLABoundaryGOKUL
Content-Disposition: form-data; name=img_two; filename=image.jpg
Content-Type:image/jpeg
//Second image data appended here.
The above give data will clearly explain what going on,all the parameters and keys have been append in the data Here you can find more details about sending multipart/form.
Now simply add the above data to request by [request setHTTPBody:body];
setURL in this method add your base url of your app.
Now all we need to do is make a connection to the server and send the request.Here we use NSURLConnection to send request.Description about NSURLConnection Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
statusCode which helps to find out whether we got successful response from server. If 200 means OK, 500 means Internal Server Error, etc.. more details here .
Handle the error in else case.
FYI I have explained what i can,refer the links for better understanding.
EDIT:
Just change the name in imageParamater array,To satisfy your requirement changed img_one & img_two with image.
- (IBAction)Done:(id)sender{
//Change input parameters as per your requirement.
NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"1",#"user_id" ,
"XXX",#"name" ,
nil];
NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:#"Test"],nil]; //Change Test with your image name
NSArray * imageParameters = [NSArray arrayWithObjects:#"image",nil];//Added image as a key.
[self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
}
and Change Point 6 with your example base URL,
//6
[request setURL:[NSURL URLWithString:#"http://google.com/files/upload.php?"]];

I think it's Helpful for you...
- (void)sendImageToServer
{
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *base64 = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *strImage = [NSString stringWithFormat:#"data:image/png;base64,%#",base64];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:strImage,#"image", nil];
NSError * err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
NSString *UserProfileInRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *data=[UserProfileInRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *len = [NSString stringWithFormat:#"%ld", (unsigned long)[data length]];
// Init the URLRequest
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:#"http://YOUR_URL"]];
[req setHTTPMethod:#"POST"];
[req setValue:len forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:req completionHandler:^(NSData *dt, NSURLResponse *response, NSError *err){
//Response Data
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:dt options:kNilOptions error:&err];
NSLog(#"%#", [dic description]);
}]resume];
}

Use AFNetworking For this task which will give very easy and reliable solution.

Related

How to post multipath image in Objective C using NSURLSession and NSJSONSerialization?

NSString *BoundaryConstant = #"----------V2ymHFg03ehbqgZCaKO6jy";
// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = #"picture";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:strUrl];
// 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];
Is FileParamConstant name is backend side multipath image folder name? It is same name I have set but why it's not working?
Below code is perfectly working , and yes FileParamConstant is the name of your backend side folder where image is store:
NSMutableDictionary * dictParam = [[NSMutableDictionary alloc]init];
[dictParam setObject:[dlf objectForKey:KEY_LOGIN_USER_ID] forKey:#"userId"];
[dictParam setObject:FirstNametextField.text forKey:#"first_name"];
[dictParam setObject:LastNametextField.text forKey:#"last_name"];
[dictParam setObject:MobileNumbertextField.text forKey:#"contact_no"];
[dictParam setObject:AddressTetField.text forKey:#"address"];
[dictParam setObject:photoselect forKey:#"is_upload"];
NSString *strUrl=[NSString stringWithFormat:#"%#update_worker_profile?",WEB_SERVICE_URL];
// 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 = #"picture";
// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:strUrl];
// 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 dictParam) {
[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", [dictParam objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
CGSize newSize = CGSizeMake(200.0f, 200.0f);
UIGraphicsBeginImageContext(newSize);
[Workerprofileimage.image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
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];
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setURL:requestURL];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"dataResponds=%#",dataResponse);
dispatch_async(dispatch_get_main_queue(), ^{
if ([[dataResponse objectForKey:#"status"] isEqualToString:#"success"]) {
}else{
NSLog(#"no");
}
});
}] resume];
}

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!

upload image to web service from database using xcode

I want to upload a image from phone to web service my link is like below as sample
"http://sample.com/upload_image.php"
my code is as below for post:
-(IBAction) post:(id) sender
{
count = 0;
self.progress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
self.progress.center = self.view.center;
progress.hidden = NO;
[self.view addSubview:self.progress];
nmyTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(updateUI:) userInfo:nil repeats:YES];
NSString *filename = [NSString alloc];
filename = [self randomStringWithLength:5];
NSData *imageData = UIImageJPEGRepresentation(imageView.image, 100);
NSError *error;
NSData *searchData;
NSHTTPURLResponse *response;
// setting up the URL to post to
NSString *urlString = #"http://dev9.edisbest.com/upload_image.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
/*
add some header info now
we always need a boundary when we post a file
also we need to set the content type
You might want to generate a random boundary.. this is just the same
as my output from wireshark on a valid html post
*/
NSString *boundary = [NSString stringWithString:#"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
/*
now lets create the body of the post
*/
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
searchData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",response);
NSString *imageName;
imageName = [[NSString alloc] initWithData:searchData encoding:NSUTF8StringEncoding];
NSLog(#"retrun Result of Upload Photo.. %#",imageName);
[request setHTTPBody:body];
// now lets make the connection to the web
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{ NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]); }];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
///self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#",returnString);
}
when i build and run i will be asked to choose image and when i select an image to upload
I got a message as the following
**[Switching to process 553 thread 0x4e03]
2015-04-28 12:08:12.856 image-video-upload[553:207] (null)
2015-04-28 12:08:12.857 image-video-upload[553:207] retrun Result of Upload Photo..
2015-04-28 12:08:12.889 image-video-upload[553:207] Finished with status code: 0**
Above message shown in my console and crashed
Try this..
UIImage *image=[UIImage imageNamed:#"i3.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64EncodedStringWithOptions:0];
NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:encodedString forKey:#"imageData"];
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
options:kNilOptions
error:&error];
NSString *urlString = #"http://Your url";
NSURL *url = [NSURL URLWithString:urlString];
// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"json" forHTTPHeaderField:#"Data-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&theResponse
error:&errorReturned];
Here is the code from my project to upload image
// 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 = UIImageJPEGRepresentation(imageToPost, 1.0);
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:[[NSString stringWithString:#"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:#"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// set URL
[request setURL:requestURL];

POST json string in NSURLSession

In my iOS app I am posting json string to server using NSURLConnection like this.
post_string = #"{"function":"getHuddleDetails", "parameters": {"user_id": "167","location_id": "71","huddle_id": "328","checkin_id": "1287"},"token":""}"
-(void)myServerRequests:(NSString *)post_string{
NSData *postData = [post_string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.myServerURl.com/jsonpost"]];
[request setTimeoutInterval:100];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData alloc]init];
}
}
And posting multipart/form-data (not JSON) using NSURLSession using below code
-(void)myFunction:(NSString *)user_name paswd:(NSString *)pass_word {
NSString *boundary = [self boundaryString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.myServerURl.com/formpost"]];
[request setHTTPMethod:#"POST"];
[request addValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary] forHTTPHeaderField:#"Content-Type"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"username\"\r\n\r\n%#", user_name] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"password\"\r\n\r\n%#", pass_word] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSAssert(!error, #"%s: uploadTaskWithRequest error: %#", __FUNCTION__, error);
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
}];
[task resume];
}
This works perfectly fine with NSURLSession, but when I tried to post json string (converted it to NSDATA and posted using NSURLSession), it is not working.
Why it happens ?
Thanks in advance
If you want to send JSON to a server you should set the content type accordingly to application/json and your content is actually just that: the JSON encoded preferably in UTF-8.
In your method myServerRequests: you set content type application/x-www-form-urlencoded - but you don't setup the corresponding content correctly. How to do this can be read here: URL-encoded form data. Additionally, specifying a charset parameter has no effect at all.
In case you want to send a string parameter for a application/x-www-form-urlencoded content type, you should also not use a lossy conversion. Instead use UTF-8. Note that NSStrings length returns the number of UTF-16 code points - which is not the same as the number of bytes of an UTF-8 encoded string.
Recap:
Don't use application/x-www-form-urlencoded content type. Instead:
Content-Type = application/json
Content-Length = <length in bytes of the UTF-8 encoded JSON>
When you fix these issues, the request should be OK.
When using a multipart/form-data request I strongly recommend to use a network library. Doing this by hand is too error prone and you would need to read at least 300 RFCs to know that you are doing it correctly ;)

Upload image file ios - Multipart format

Here is the webserice call
URL: http://mywedshare.com/wp-admin/admin-ajax.php?action=app_photoupload
gallery_ID,guestName, guestEmail, guestPasscode,photo_file (Multipart File Format)
I need to upload an UIImage. Im getting my NSData using the following line -
imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 1);
and uploading it using
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set Params
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
//Create boundary, it can be anything
NSString *boundary = #"------VohpleBoundary4QuqLuM1cE5lMwCy";
// 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];
//Populate a dictionary with all the regular values you would like to send.?action=app_photoupload?
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:#"app_photoupload" forKeyPath:#"action"];
[parameters setValue:galleryID forKey:#"gallery_ID"];
[parameters setValue:galleryName forKey:#"guestName"];
[parameters setValue:guestEmail forKey:#"guestEmail"];
[parameters setValue:guestPasscode forKey:#"guestPasscode"];
// add params (all params are strings)
for (NSString *param in parameters) {
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"%#\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
NSString *FileParamConstant = #"photo_file";
NSData *imageData2 = imageData;
//Assuming data is not nil we add this to the multipart form
if (imageData2)
{
[body appendData:[[NSString stringWithFormat:#"--%#\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"%#\"; filename=\"wedshare.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[#"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData2];
[body appendData:[[NSString stringWithFormat:#"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
//Close off the request with the boundary
[body appendData:[[NSString stringWithFormat:#"--%#--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the request
[request setHTTPBody:body];
// set URL
NSString *url = #"http://mywedshare.com/wp-admin/admin-ajax.php";
[request setURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([httpResponse statusCode] == 200) {
[HUD showUIBlockingIndicatorWithText:#"Success"];
[HUD hideUIBlockingIndicator];
NSLog(#"success");
}
}];
Im getting Success but the image itself is not being uploaded onto the server. Please help me.
I'd suggest:
Run the app on the simulator and run Charles (or something like it) at the same time, and make sure the request looks ok. I don't see anything obviously wrong here from the client side. Still, Charles can tell us if the request looks ok.
I obviously cannot speak to the server side of it (e.g. the choice of the photo_file field name, the other properties, etc.). How confident are you regarding the API?
You are declaring success if the statusCode is 200. The 200 is a HTTP level status code that means is that the request was received and the server responded successfully, but it doesn't necessarily mean that the upload was successful. It looks like that URL returns some code, and you might want to examine that value before you start declaring success.

Resources