URLSession中的任务完成后返回值

问题描述 投票:0回答:1

我想做的是,当我从另一个类向-(void)downloadTaskStart发送消息然后获得bytesWritten值(我使用单例)时,它将在任务完成后返回该值(无论是否有错误),不是最初一毫秒的值。感谢任何帮助!

    @interface DownloadManager ()
    @property (nonatomic, strong) NSString *bytesWritten;

    @end

    @implementation DownloadManager

    - (void)downloadTaskStart {
        NSURL  *url = [NSURL URLWithString:@"http://somehost.com/somefile.zip];
        NSMutableURLRequest *downloadRequest = [NSMutableURLRequest requestWithURL:url
                                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                                   timeoutInterval:60];
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:config
                                                                      delegate:self
                                                                 delegateQueue:[NSOperationQueue mainQueue]];


        downloadTask = [downloadSession downloadTaskWithRequest:downloadRequest];
        startTime = [NSDate timeIntervalSinceReferenceDate];
        [downloadTask resume];

    }

    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
        if (error) {
            NSLog(@"Error when download: %@", error);
        } 

        //do something?
    }

    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
        //do something?
    }

    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {            
        self.bytesWritten = [@(totalBytesWritten) stringValue];
    }

    @end
ios objective-c cocoa-touch
1个回答
0
投票

您可以使用

© www.soinside.com 2019 - 2024. All rights reserved.