Objective C - POST data using NSURLConnection

后端 未结 4 1026
独厮守ぢ
独厮守ぢ 2021-02-10 17:33

I\'m very slowly working my way through learning the URL loading system for iOS development, and I am hoping someone could briefly explain the following piece of code:



        
4条回答
  •  无人及你
    2021-02-10 18:38

    please use below code.
    +(void)callapi:(NSString *)str withBlock:(dictionary)block{
    
    NSData *postData = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@“%@/url”,WebserviceUrl]]
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                          timeoutInterval:120.0];
    
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody:postData];
    
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if (!data) {
             NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
              [dict setObject:[NSString stringWithFormat:@"%@",AMLocalizedString(SomethingWentWrong, nil)] forKey:@"error"];
             block(dict);
             return ;
         }
         NSError *error = nil;
         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
         //////NSLog(@"%@",dict);
         if (!dict) {
             NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
             [dict setObject:AMLocalizedString(ServerResponceError, nil) forKey:@"error"];
             block(dict);
             return ;
         }
         block(dict);
    
     }];
    }
    

提交回复
热议问题