0

What I did is that I can able to select an image/video/file from my iOS Device by using HSAttachmentPicker library.

In log I am getting file name with its extention and NSData/Base64 Encoded string.

Now I want to send this data through post API call.

Here is the my API call and its parameters,

Example:

http://www.jamboreebliss.com/sayar/public/api/v1/helpdesk/create?api_key=9p41T2XFZ34YRZJUNQAdmM7iV0Rr1CjN&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI5LCJpc3MiOiJodHRwOi8vd3d3LmphbWJvcmVlYmxpc3MuY29tL3NheWFyL3B1YmxpYy9hcGkvdjEvYXV0aGVudGljYXRlIiwiaWF0IjoxNTIzMDA5MzUzLCJleHAiOjE1MjMwMDk1OTMsIm5iZiI6MTUyMzAwOTM1MywianRpIjoiVFBXbmpHalpDZXdYQVFBViJ9.q6v0mvT9R9G5sx2P4jlTAWfUEKcnOPqyjjJsVTZEWvs&subject=Sample subject&first_name=Poonam&last_name=Patil&email=poonam.h1212@gmail.com

in this API call, http://www.jamboreebliss.com/sayar/public is my base URL,

api/v1/helpdesk/create this is the main API

and parameters are, api_key, token, first_name, last_name, email

up to this, it is working fine.

Now what I want is I want to send/forward/upload an attachment/data in this API call,

its parameter name is media_attachment[] which takes a file.

I tried in Postman API its works fine (see below screenshot)

enter image description here

But I do not know how to implement this feature. (I do not know how to write code for this in xocde)

How to call API call with media_attachment[] parameter its value i.e file data?

Here is working code (without attachment)

// CreateTicket.m file

-(void)sumbitButtonClicked
{
    if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
        //connection unavailable
        [utils showAlertWithMessage:NO_INTERNET sendViewController:self];

    }else{


        NSString *url=[NSString stringWithFormat:@"%@helpdesk/create?api_key=%@&token=%@&subject=%@&first_name=%@&last_name=%@&email=%@",[userDefaults objectForKey:@"companyURL"],API_KEY,[userDefaults objectForKey:@"token"],_subjectView.text,_firstNameView.text,_lastNameView.text,_emailTextView.text];

MyWebservices *webservices=[MyWebservices sharedInstance];

[webservices httpResponsePOST:url parameter:@"" callbackHandler:^(NSError *error,id json,NSString* msg) {
                [[AppDelegate sharedAppdelegate] hideProgressView];

                if (error || [msg containsString:@"Error"]) {


                //some code

                }else if(error)  {
                        [self->utils showAlertWithMessage:[NSString stringWithFormat:@"Error-%@",error.localizedDescription] sendViewController:self];

                    }
     if (json) {

       NSLog(@"JSON-CreateTicket-%@",json);


      }


}

Webservices.m file

 -(void)httpResponsePOST:(NSString *)urlString
                  parameter:(id)parameter
            callbackHandler:(callbackHandler)block{
        NSError *err;

        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];



        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

        [request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Offer-type"];
        [request setTimeoutInterval:45.0];

        NSData *postData = nil;
        if ([parameter isKindOfClass:[NSString class]]) {
            postData = [((NSString *)parameter) dataUsingEncoding:NSUTF8StringEncoding];
        } else {


            postData = [NSJSONSerialization dataWithJSONObject:parameter options:kNilOptions error:&err];
        }
        [request setHTTPBody:postData];
        //[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameter options:nil error:&err]];

        [request setHTTPMethod:@"POST"];
        //
        NSLog(@"Request body %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
        NSLog(@"Thread--httpResponsePOST--Request : %@", urlString);
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] ];


        [[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
            if (error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    block(error,nil,nil);
                });
                NSLog(@"dataTaskWithRequest error: %@", [error localizedDescription]);

            }else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

                NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];

                if (statusCode != 200) {
                    NSLog(@"dataTaskWithRequest HTTP status code: %ld", (long)statusCode);


                        }

                NSString *replyStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];




                NSError *jsonerror = nil;

                id responseData =  [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonerror];

                dispatch_async(dispatch_get_main_queue(), ^{
                    block(jsonerror,responseData,nil);
                });

            }

        }] resume];

    }
Nikita Patil
  • 674
  • 1
  • 7
  • 17
  • 2
    you have to use multipart uploading, refer from here -> https://stackoverflow.com/questions/22334690/ios-upload-file-with-multipartform-data – dahiya_boy Apr 10 '18 at 12:11
  • in your postman you have a button upright called **Code**, you can choose some programming languages. It is NOT to be copied and pasted, but CAN give you some hints – GIJOW Apr 10 '18 at 12:34
  • in your case you should try Using some third party library like AFNetworking Alamofire etc. – Abu Ul Hassan Apr 10 '18 at 12:37
  • ok, Sir. Let me check it once. – Nikita Patil Apr 10 '18 at 12:49
  • @GIJOW ha just now I checked, Postman provides some codes. That helps me. I am getting some issues let me check it once. – Nikita Patil Apr 11 '18 at 11:09

0 Answers0