NSURLConnection and grand central dispatch

后端 未结 3 373
-上瘾入骨i
-上瘾入骨i 2020-11-29 16:47

Is it advisable to wrap up NSUrlConnection in a gcd style blocks and run it on a low_priority queue?

I need to ensure that my connections are not happening on the ma

3条回答
  •  独厮守ぢ
    2020-11-29 17:41

    Have a look at this code block:

    -(void)getDataFromServer
    {
        NSDictionary *dicParams = [NSDictionary dictionaryWithObjectsAndKeys:
                               userId,    kUserID,
                               pageIndex,kPageIndex,
                               nil];
    
        NSString *yourURL = [self addQueryStringToUrlString:[NSString stringWithFormat:@"%@/%@",_PATH_,apiName] withDictionary:dicParams];
    
    
        NSString *queue_id = @"_queue_id_";
        dispatch_queue_t queue = dispatch_queue_create([queue_id UTF8String], 0);
        dispatch_queue_t main = dispatch_get_main_queue();
    
        dispatch_async(queue, ^{
    
            NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:yourURL] 
                                                        cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                                    timeoutInterval:60.0];
            [theRequest setHTTPMethod:@"GET"];
            [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [theRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
            NSError        *serviceError = nil;
            NSURLResponse  *serviceResponse = nil;
            NSData *dataResponse = [NSURLConnection sendSynchronousRequest:theRequest 
                                                         returningResponse:&serviceResponse 
                                                                     error:&serviceError];
    
            if(serviceError)
            {
                dispatch_sync(main, ^{
    
                    // Update your UI
    
                    if(serviceError.code == -1012){
                        // Log error
                    }else{
                        // Log error
                    }
                });
            }
    
            else
            {
                NSError *jsonError = nil;
    
                id dataObject = [NSJSONSerialization JSONObjectWithData:dataResponse 
                                                                options:kNilOptions 
                                                                  error:&jsonError];
                NSMutableArray *arrResponse = (NSMutableArray *)dataObject;
    
                dispatch_sync(main, ^{
    
                    // Update your UI
                    [yourTableView reloadData];
                });
            }
        });
    }
    
    +(NSString*)addQueryStringToUrlString:(NSString *)urlString withDictionary:(NSDictionary *)dictionary
    {
        NSMutableString *urlWithQuerystring = [[NSMutableString alloc] initWithString:urlString];
    
        for (id key in dictionary) {
            NSString *keyString = [key description];
            NSString *valueString = [[dictionary objectForKey:key] description];
    
            if ([urlWithQuerystring rangeOfString:@"?"].location == NSNotFound) {
                [urlWithQuerystring appendFormat:@"?%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
            } else {
                [urlWithQuerystring appendFormat:@"&%@=%@", [self urlEscapeString:keyString], [self urlEscapeString:valueString]];
            }
        }
        return urlWithQuerystring;
    }
    
    +(NSString*)urlEscapeString:(NSString *)unencodedString
    {
        CFStringRef originalStringRef = (__bridge_retained CFStringRef)unencodedString;
        NSString *s = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,originalStringRef, NULL, NULL,kCFStringEncodingUTF8);
        CFRelease(originalStringRef);
        return s;
    }
    

提交回复
热议问题