iOS:如何调用post方法,其中包含一些参数和文件(附件)?

时间:2018-04-10 12:09:12

标签: ios api nsdate postman attachment

我所做的是我可以使用HSAttachmentPicker库从iOS设备中选择图像/视频/文件。

在日志中我得到文件名及其扩展名和NSData / Base64编码字符串。

现在我想通过post API调用发送这些数据。

这是我的API调用及其参数

示例:

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

在此API调用中,http://www.jamboreebliss.com/sayar/public是我的基本网址

api/v1/helpdesk/create这是主要的API

和参数包括api_keytokenfirst_namelast_nameemail

到目前为止,它工作正常。

现在我想要的是我想在此API调用中发送/转发/上传附件/数据,

其参数名称为media_attachment[],其中包含一个文件。

我在Postman API中尝试过它的工作正常(见下面的截图)

enter image description here

但我不知道如何实现此功能。 (我不知道如何在xocde中编写代码)

如何使用media_attachment[]参数调用API调用其值,即文件数据?

这是工作代码(没有附件)

// 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文件

 -(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];

    }

0 个答案:

没有答案