Reputation: 115
I have written a method with completion block in nsobject class and call this method from uiviewcontroller, its working perfectly but how do I pass a nsstring parameter in this method ,following is my pice of code.
-(void)testingFunction:(void(^)(NSMutableArray* result))handler{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]];
NSString *authStr = @"";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
//create the task
NSURLSessionDataTask* task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[dataArray addObject:[[json objectForKey:@"query"] objectForKey:@"geosearch"]];
dispatch_async(dispatch_get_main_queue(), ^{
handler(dataArray) ;
});
}];
[task resume];
}
and call this method from my uiviewcontroller
[[AllFunction sharedInstance] testingFunction:^(NSMutableArray* testResult){
[somearray addObject:testResult];
NSLog(@"Result was %@", somearray);
[self.tableView reloadData];
}];
Upvotes: 4
Views: 2533
Reputation: 1532
If you want to pass a NSString*
to the method:
-(void)testingFunction:(void(^)(NSMutableArray* result))handler andString:(NSString*) yourString;
Or if you want to pass a NSString*
to the completion block:
-(void)testingFunction:(void(^)(NSMutableArray* result, NSString* yourString))handler;
Edit:
You can call the method like this:
NSString* yourString = @"Some Text";
testingFunction:^(NSMutableArray* result) {
//Do whatever you want here
} andString:yourString;
Go read this: http://www.tutorialspoint.com/objective_c/objective_c_functions.htm
EDIT2:
As trojanfoe said, if your string is supposed to be an url you should use NSURL
instead of NSString
Upvotes: 6
Reputation: 122468
As this "string" is really a URL, pass an NSURL
instance instead:
-(void)testingFunction:(void(^)(NSMutableArray* result))handler
withURL:(NSURL *)url
{
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
....
}
However I am unsure why your question is entitled "completion block with parameters" as this question relates to an ordinary method.
Upvotes: 0