2015-10-15 146 views

回答

2
- (void) loginRequest:(NSString*) username withPassword:(NSString *) password callback:(void (^)(NSError *error, BOOL success))callback 
{ 
    NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request 
                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){ 
     if (error) { 
      // Handle error, optionally using 
      callback(error, NO); 
     } 
     else { 
      callback(nil, YES); 
     } 
    }]; 

    [dataTask resume]; 
} 

調用此方法像這樣:

[self loginRequest:@"myUsername" password:@"password" callback:^(NSError *error, BOOL success) { 
    if (success) { 
     NSLog(@"My response back from the server after an unknown amount of time"); 
    } 
    else { 
     NSLog(@"%@", error); 
    } 
}]; 
1

讓剛做dataTaskWithRequest完成塊任務。 直到您可以顯示活動指示符以阻止用戶觸摸屏幕上的任何內容爲止。

例子:

activityIndicator.startAnimating() 

let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in 
    activityIndicator.stopAnimating() 
    // do your stuff here 

}); 
4

我認爲,這種方法是類

NSURLSessionDataTask *task = [defaultSession dataTaskWithRequest:request 
               completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) 
{ 
    // code after completion of task 
}]; 
[task resume]; 
5

內明顯如果你真的需要同步請求時,你可以使用信號燈

我已在NSURLSession上實施了一個小類別來提供此功能。

.H文件:

@import Foundation.NSURLSession; 

@interface NSURLSession (Additions) 

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error; 

@end 

.M文件:

@implementation NSURLSession (Additions) 

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse *__autoreleasing *)responsePointer error:(NSError *__autoreleasing *)errorPointer 
{ 
    dispatch_semaphore_t semaphore; 
    __block NSData *result = nil; 

    semaphore = dispatch_semaphore_create(0); 

    void (^completionHandler)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error); 
    completionHandler = ^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) 
    { 
     if (errorPointer != NULL) 
     { 
      *errorPointer = error; 
     } 

     if (responsePointer != NULL) 
     { 
      *responsePointer = response; 
     } 

     if (error == nil) 
     { 
      result = data; 
     } 

     dispatch_semaphore_signal(semaphore); 
    }; 

    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:completionHandler] resume]; 

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 

    return result; 
} 

@end 
+0

這是正確的做法。 –

+0

不幸的是,這是崩潰* errorPointer =錯誤;我無法使用它。 –

+0

@AlexZavatone你能告訴我你如何調用這個方法嗎?具體如何聲明錯誤的指針 –