问题描述
我创建了一个名为" ConnectionManager "的类,该类将处理所有网络请求并从服务器中获取数据,并在调用完成处理程序之后.
I've created a class called "ConnectionManager" that will handle all network request and fetch data from the server and after that call to a completion handler.
ConnectionManager.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "UIAlertView+CustomAlertView.h"
#import <Crashlytics/Crashlytics.h>
@interface ConnectionManager : NSObject<NSURLSessionDataDelegate>
@property (weak, nonatomic) NSMutableData *receivedData;
@property (weak, nonatomic) NSURL *url;
@property (weak, nonatomic) NSURLRequest *uploadRequest;
@property (nonatomic, copy) void (^onCompletion)(NSData *data);
@property BOOL log;
-(void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *data))completionHandler;
-(void)uploadDataWithRequest:(NSURLRequest*)request withCompletionHandler:(void (^)(NSData *data))completionHandler;
@end
ConnectionManager.m
#import "ConnectionManager.h"
@implementation ConnectionManager
-(void)uploadDataWithRequest:(NSURLRequest*)request withCompletionHandler:(void (^)(NSData *data))completionHandler{
// Instantiate a session configuration object.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Configure Session Configuration
[configuration setAllowsCellularAccess:YES];
// Instantiate a session object.
NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
// Assign request for later call
self.uploadRequest = request;
// Create an upload task object to perform the data uploading.
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:self.uploadRequest fromData:nil];
// Assign completion handler
self.onCompletion = completionHandler;
// Inititate data
self.receivedData = [[NSMutableData alloc] init];
// Resume the task.
[task resume];
}
-(void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *data))completionHandler{
// Instantiate a session configuration object.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Configure Session Configuration
[configuration setAllowsCellularAccess:YES];
// Instantiate a session object.
NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
// Assign url for later call
self.url = url;
// Create a data task object to perform the data downloading.
NSURLSessionDataTask *task = [session dataTaskWithURL:self.url];
// Assign completion handler
self.onCompletion = completionHandler;
// Inititate data
self.receivedData = [[NSMutableData alloc] init];
// Resume the task.
[task resume];
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[self.receivedData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error) {
if (error.code == -1003 || error.code == -1009) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to connect to the server. Please check your internet connection and try again!" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"retry",nil];
[alert showWithCompletion:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex==1) {
// Retry
if (self.url) {
NSURLSessionDataTask *retryTask = [session dataTaskWithURL:self.url];
[retryTask resume];
}else{
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:self.uploadRequest fromData:nil];
[task resume];
}
}else{
self.onCompletion(nil);
}
}];
}];
}else{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An unkown error occured! Please try again later, thanks for your patience." delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"retry",nil];
[alert show];
CLS_LOG(@"Error details: %@",error);
self.onCompletion(nil);
}];
}
}
else {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.onCompletion(self.receivedData);
}];
}
}
@end
这是我用来称呼的那段代码:
Here is the piece of code I use to call it :
-(void)loadDataFromServer{
NSString *URLString = [NSString stringWithFormat:@"%@get_people_number?access_token=%@", global.baseURL, global.accessToken];
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:URLString];
ConnectionManager *connectionManager = [[ConnectionManager alloc] init];
[connectionManager downloadDataFromURL:url withCompletionHandler:^(NSData *data) {
if (data != nil) {
// Convert the returned data into an array.
NSError *error;
NSDictionary *number = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) {
CLS_LOG(@"Error: %@, Response:%@",error,[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
else{
[_mapView updateUIWithData:[number objectForKey:@"number"]];
}
}
}];
}
我发现使用Instruments时,即使从服务器获取数据并调用完成处理程序,ConnectionManager类型的所有对象仍然是持久的.
I figured out when using Instruments that All objects of ConnectionManager type are persistent even after getting the data from server and calling the completion handler.
我试图将完成处理程序属性从copy更改为strong,但是得到了相同的结果.将其更改为弱会导致崩溃,并且永远不会被调用.
I tried to change the completion handler property from copy to strong, but I got the same results. Changing it to weak cause a crash and it never be called.
请有人指导我正确的方法.
Please someone guide me to the right way.
推荐答案
经过大量研究,我发现URL会话对象仍然存在.
After doing a lot of research, I found that the URL Session object is still alive.
基于 Apple文档生命周期URL Session 的情况有两种:
-
使用系统提供的委托(不设置委托),此处系统将负责使NSURLSession对象无效.
Using the system provided delegate (by not setting a delegate), here the system will take care of invalidating the NSURLSession object.
使用自定义委托.当您不再需要会话时,可以通过调用invalidateAndCancel(以取消未完成的任务)或finishTasksAndInvalidate(以允许未完成的任务在使对象无效之前完成)来使会话无效.
Using a custom delegate. When you no longer need a session, invalidate it by calling either invalidateAndCancel (to cancel outstanding tasks) or finishTasksAndInvalidate (to allow outstanding tasks to finish before invalidating the object).
要修复上面的代码,我只更改了委托方法"didCompleteWithError",如下所示:
To fix the code above I only changed the delegate method "didCompleteWithError" like the following:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error) {
if (error.code == -1003 || error.code == -1009) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to connect to the server. Please check your internet connection and try again!" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"retry",nil];
[alert showWithCompletion:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex==1) {
// Retry
if (self.url) {
NSURLSessionDataTask *retryTask = [session dataTaskWithURL:self.url];
[retryTask resume];
}else{
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:self.uploadRequest fromData:nil];
[task resume];
}
}else{
[session finishTasksAndInvalidate];
self.onCompletion(nil);
}
}];
}];
}else{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An unkown error occured! Please try again later, thanks for your patience." delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"retry",nil];
[alert show];
[session finishTasksAndInvalidate];
self.onCompletion(nil);
}];
}
}
else {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[session finishTasksAndInvalidate];
self.onCompletion(self.receivedData);
}];
}
}
这篇关于ARC的iOS内存管理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!