OC中下载网络图片到本地


#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {

    @autoreleasepool {

        // insert code here...

//https://www.baidu.com/img/bd_logo1.png

//        NSURL *url = [NSURL URLWithString:@"https://www.baidu.com/img/bd_logo1.png"];

//http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg

        NSURL *url = [NSURL URLWithString:@"http://www.xinhuanet.com/photo/2018-03/13/1122528717_15209051820841n.jpg"];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        NSError *err;

        //save the data in binary

        

        NSData *data = [NSURLConnection sendSynchronousRequest:request

                                             returningResponse:NULL

                                                         error:&err];

        

        

        if(!data) {

            NSLog(@"Fetch failed : %@", [err localizedDescription]);

        }

        NSLog(@"The file is %lu bytes", (unsigned long)[data length]);

        

        BOOL written = [data writeToFile:@"/Users/demi/Ming/test/renda.jpg" options:0 error:&err];

        

        if(!written) {

            NSLog(@"Write failed : %@", [err localizedDescription]);

        }

        NSLog(@"Success");

        

    }

    return 0;

}

Result:

2018-03-13 21:27:13.703527+0800 TOCSaveNSDataa[64376:3910850] The file is 137361 bytes

2018-03-13 21:27:13.719984+0800 TOCSaveNSDataa[64376:3910850] Success

Program ended with exit code: 0


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 iOS 开发,可以使用 AVPlayer 来播放音频,但是默认情况下 AVPlayer 不支持音频下载功能。不过,我们可以通过一些方法来实现音频下载。 一种方法是使用 AVAssetExportSession,将音频文件导出为本地文件。具体步骤如下: 1. 创建 AVURLAsset 对象,用于获取音频资源。 2. 创建 AVAssetExportSession 对象,用于导出音频资源。 3. 设置 AVAssetExportSession 的输出路径和输出格式。 4. 调用 exportAsynchronouslyWithCompletionHandler 方法开始导出音频资源。 5. 在 completion handler 获取导出的本地音频文件路径,然后使用 AVPlayer 播放该文件。 示例代码如下: ```objc // 获取音频资源 AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:@"http://example.com/audio.mp3"]]; // 创建导出会话 AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:asset presetName:AVAssetExportPresetAppleM4A]; // 设置输出路径和格式 NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"audio.m4a"]; exportSession.outputURL = [NSURL fileURLWithPath:outputPath]; exportSession.outputFileType = AVFileTypeAppleM4A; // 开始导出 [exportSession exportAsynchronouslyWithCompletionHandler:^{ switch (exportSession.status) { case AVAssetExportSessionStatusCompleted: { // 获取导出的本地文件路径 NSString *localPath = exportSession.outputURL.path; // 使用 AVPlayer 播放本地文件 AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:localPath]]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; [player play]; break; } case AVAssetExportSessionStatusFailed: NSLog(@"导出失败:%@", exportSession.error); break; default: break; } }]; ``` 另一种方法是使用 AVAssetResourceLoaderDelegate,通过响应 NSURLSessionDataTask 的回调来实现音频下载。具体步骤如下: 1. 创建 AVURLAsset 对象,设置其 resourceLoader 的代理为自定义的 AVAssetResourceLoaderDelegate 对象。 2. 在代理对象实现 resourceLoader:shouldWaitForLoadingOfRequestedResource: 方法,该方法会在播放器请求某个资源时被调用。 3. 在该方法,创建一个 NSURLSessionDataTask 对象,使用该对象下载资源,并将下载完成的数据通过 AVAssetResourceLoadingRequest 的 respondWithData: 方法返回给播放器。 4. 在代理对象实现 resourceLoader:didCancelLoadingRequest: 方法,该方法会在播放器不再需要请求某个资源时被调用,可以在该方法取消 NSURLSessionDataTask 对象。 示例代码如下: ```objc @interface CustomAVAssetResourceLoaderDelegate : NSObject<AVAssetResourceLoaderDelegate> @property (nonatomic, strong) NSURLSession *session; @end @implementation CustomAVAssetResourceLoaderDelegate - (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest { // 创建 NSURLSessionDataTask 对象,下载资源 NSURLSessionDataTask *task = [self.session dataTaskWithURL:loadingRequest.request.URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { [loadingRequest finishLoadingWithError:error]; } else { // 将下载完成的数据返回给播放器 [loadingRequest.dataRequest respondWithData:data]; [loadingRequest finishLoading]; } }]; [task resume]; return YES; } - (void)resourceLoader:(AVAssetResourceLoader *)resourceLoader didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest { // 取消 NSURLSessionDataTask 对象 [self.session invalidateAndCancel]; } @end // 获取音频资源 AVURLAsset *asset = [AVURLAsset assetWithURL:[NSURL URLWithString:@"http://example.com/audio.mp3"]]; // 设置 resourceLoader 的代理为自定义的 AVAssetResourceLoaderDelegate 对象 CustomAVAssetResourceLoaderDelegate *delegate = [[CustomAVAssetResourceLoaderDelegate alloc] init]; delegate.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [asset.resourceLoader setDelegate:delegate queue:dispatch_get_main_queue()]; // 使用 AVPlayer 播放音频 AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset]; AVPlayer *player = [AVPlayer playerWithPlayerItem:item]; [player play]; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值