【问题标题】:how to make asynchronous Mutable request and getting only last request value and canceling all request before last request如何进行异步可变请求并仅获取最后一个请求值并在最后一个请求之前取消所有请求
【发布时间】:2017-01-12 06:14:14
【问题描述】:
NSError *error   = nil;


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSOperationQueue *downloadOperationQueue = [[NSOperationQueue alloc] init];
[downloadOperationQueue cancelAllOperations];

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


[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
 {
     NSLog(@"Respose %@",response.URL);
     NSString *jsonInString = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
     NSLog(@"json in string for backend: %@",jsonInString);

     [self.delegate responseConnection:data withMethodName:methodName];
     if (!error)
     {
         // did finish logic here, then tell the caller you are done with success
         // completion(YES, nil);
     }
     else
     {
         // otherwise, you are done with an error
         //  completion(NO, error);
     }
 }];

【问题讨论】:

  • 你为什么不用NSURLSession
  • 是的,我有那段代码,但你能告诉我用下面的代码得到它吗:
  • NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { } else { } }];

标签: ios objective-c nsoperation nsoperationqueue nsjsonserialization


【解决方案1】:

对于NSURLSession

你可以使用[NSURLSession cancelPreviousPerformRequestsWithTarget:self];

也适用于NSURLConnection

你可以使用[NSURLConnection cancelPreviousPerformRequestsWithTarget:self];

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 2014-07-03
    • 2016-08-27
    • 2020-07-06
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多