【问题标题】:Return value after task completed in URLSessionURLSession 中任务完成后的返回值
【发布时间】:2015-11-26 06:15:25
【问题描述】:

我想要做的是当我从另一个类向-(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】:

你可以使用

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error 

NSURLSession 的方法,因为它会在任务完成时调用,如果出现错误并传递值,请使用 DelegatesNSNotification

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多