ios - 如何在没有 afnetworking 的情况下使用 get 请求将数组作为参数发送到 url

标签 ios objective-c arrays nsurlsession

我必须使用 get 请求将数组作为参数之一发送到 url,url 是 http://13.229.45.226/api/resource/Employee/?filters=[[ “员工”,“company_email”,“=”,“susee@lektrify.club”]]。我正在使用 nsurl session 进行 api 调用。

请找到下面的代码

NSArray *myArray = @[@"Employee",@"company_email",@"=",Emailid];


NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];

NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonString);

NSString *urlstr= [NSString stringWithFormat:@"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%@]",jsonString];

 NSLog(@"%@",urlstr);

[apicall getDictionaryFromApiwithoutlogin:urlstr restfulType:kRestfulGet andUseContentType:NO withRequestBody:nil withheader:YES completionHandler:^(NSDictionary *result){
    dispatch_async(dispatch_get_main_queue(), ^{ }];

这是为我正在提供输入的敌人调用通用 API 编写的代码。

    -(void)getDictionaryFromApiwithoutlogin:(NSString *)url restfulType:(NSInteger)restfulType andUseContentType:(BOOL)useContentType withRequestBody:(NSData*)httpBody withheader:(BOOL)header completionHandler:(void (^)(NSDictionary *isSuccess))isSuccess
{

loginstatus = [[NSUserDefaults standardUserDefaults] boolForKey:@"loginStatus"];

    if (![APICall hasNetwork])
    {
        //  [customBezelActivityView removeViewAnimated:YES];
        // [Util displayToastMessage:@"No internet connection"];
        return;
    }

    /* RESTFUL request function, all API request will come here */
    //url  = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"url:%@",url);

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:300.0];
    // set request variables
    if (restfulType == kRestfulGet) {
        [request setHTTPMethod:@"GET"];
    } else if (restfulType == kRestfulPost) {
        [request setHTTPMethod:@"POST"];
    } else if (restfulType == kRestfulPut) {
        [request setHTTPMethod:@"PUT"];
    } else {
        [request setHTTPMethod:@"DELETE"];
    }

    if (useContentType) {
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
if (header) {
    [request setValue:[NSString stringWithFormat:@"Bearer %@",[[NSUserDefaults standardUserDefaults]valueForKey:@"access_token"]] forHTTPHeaderField:@"Authorization"];
}
    if (httpBody != nil) {
        request.HTTPBody = httpBody;
    }

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil)
        {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            if ([httpResponse respondsToSelector:@selector(statusCode)])
            {
                NSInteger responseStatusCode = [httpResponse statusCode];
                NSLog(@"api response: %@", httpResponse);
                if (responseStatusCode == 200)
                {
                    NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
                    isSuccess(response);
                }else if (responseStatusCode==401)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [customBezelActivityView removeViewAnimated:YES];

                        [APICall sigininpageafteraccestokenexperise];

                    });

                }
                else if (responseStatusCode==500)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [customBezelActivityView removeViewAnimated:YES];


                        [[NSNotificationCenter defaultCenter]postNotificationName:@"usernotfound" object:nil];
                    });

                }

                else{
                    [customBezelActivityView removeViewAnimated:YES];
                    [APICall handleApiErrorCode:responseStatusCode];
                }
            }
        }else
            dispatch_async(dispatch_get_main_queue(), ^{
                [customBezelActivityView removeViewAnimated:YES];
                [Util handleErrorCodesForApi:(int)error.code];
            });
    }];
    [postDataTask resume];
    [session finishTasksAndInvalidate];


}

当我尝试在 post man 数组中链接这个 [["Employee", "company_email", "=", "xxx@xxx.club"]] 。它正在研究如何为这个数组添加到 url 并发出获取请求。

感谢您的快速回复。

最佳答案

我找到了问题的答案

解决方案是你必须创建一个数组,你必须对数据和编码字符串进行 NSJSONSerialization 这可以解决问题

NSArray *myArray = @[@"Employee",@"company_email",@"=",Emailid];

NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];

NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", jsonString);

NSString *urlstr= [NSString stringWithFormat:@"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%@]",jsonString];

请检查更新后的问题以获得完整答案

关于ios - 如何在没有 afnetworking 的情况下使用 get 请求将数组作为参数发送到 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785278/

相关文章:

ios - 相应地移动 View View 折叠/展开动画

ios - 使用 Sirikit 提高支付的安全性

ios - 在 tableview 单元格中使用 KVO 跟踪对 Swift 3 中类实例的特定属性的更改

javascript - 如何使用 DataTables 插件显示具有 2 个标题的表格?

arrays - 初始化VHDL中的记录数组

ios - 如何在 native iOS 应用程序中显示 Vimeo 实时视频流

ios - 如何在 Storyboard 中将自定义字体设置为 UILabel

ios - 拦截 UITextField touch

objective-c - 何时在 Objective-C 中使用 id?

jquery - 切换 jquery 元素集合中的元素位置