iOS8后台运行方案总结_第1页
iOS8后台运行方案总结_第2页
iOS8后台运行方案总结_第3页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、iOS 8.0后台任务长期运行方案后台运行方案实现方式为:Backgro un dRu nne叶 NSURLSession1. 配置軸MlCinaz ts infs 乱£呢讷辭Build 內曲99Build RusVoice cvsr IF9 kfl*t3tana 旳 ic3Cs Dcttnai acceissory conniricabor3 IMta BtK)ao41i L£ acCBsSdrieaj*ds 35 a E .Btcotti LE access:Parrott isMca:x&5tepi: J J4d dRcqu -2 E«?nirrtd

2、 'Joow* 唱 io)cuf pn,£ie* Keychain ShmngApp GroupsOf?- HomoKitOats Pto:Mi «i2. 在 AppDelegate 中property (assign , nonatomic ) BOOL isBackground; / 判读是否是后台运行-(void )applicationDidEnterBackground:( UIApplication*)applicationBackgroundRunner shared run;self . isBackground = yes;/在回到界面后关闭后台运

3、行-(void )applicationWillEnterForeground:( UIApplication*)application BackgroundRunner shared stop ;self .isBackground = NO;3. 手机密码锁开启后的文件保护问题设置/ 设置常量#define UrlsessionDownload #define BundleIdentifier NSBundle mainBundlebundleIdentifier/ 打开 uisesion 目录的文件保护设置为无 /创建可使用的 urlseseion 路径 -(void )createUr

4、lSessionNSString *theFMCachePath= nil;NSArray *pathes = NSSearchPathForDirectoriesInDomains (NSCachesDirect ory, NSUserDomainMask , YES);theFMCachePath = pathes objectAtIndex :0; theFMCachePath = theFMCachePath stringByAppendingString :UrlsessionDownload ;theFMCachePath = theFMCachePath stringByAppe

5、ndingString :NSString stringWithFormat :"%/" ,BundleIdentifier ;NSFileManager *fileManager = NSFileManager defaultManager ;if(!fileManagerisExecutableFileAtPath :theFMCachePath)/设置文件为无权限保护NSDictionary *attributes = NSDictionary dictionaryWithObject :NSFileProtectionNoneforKey :NSFileProtec

6、tionKey ;fileManagercreateDirectoryAtPath :theFMCachePathwithIntermediateDirectories :YESattributes :attributeserror :nil ;4上传 sessioin 的代码(, UploadSessionBackgound.h, UploadSessionBackgound.m )/Upl oadSessionBackgound.h#import <Foundation/Foundation.h>protocol UploadSessionBackgoundDelegate&l

7、t;NSObject >-(void )requestUploadFinishDictionary:( NSDictionary *)dictionary;endinterface UploadSessionBackgound : NSObject <NSURLSessionDataDelegate >property (nonatomic , strong ) NSURLSession *urlSession;property (nonatomic , strong ) NSURLSessionUploadTask *sesssionDataTask;property (n

8、onatomic , weak ) id<UploadSessionBackgoundDelegate > sessioinDelegate;-(void )startBackground:( NSMutableURLRequest *)request;-(void )stopUploadBackground;end/Upl oadSessionBackgound.m#import "UploadSessionBackgound.h"implementation UploadSessionBackgound synthesize urlSession,sesss

9、ionDataTask,sessioinDelegate;-(NSURLSession *)urlSessionstatic NSURLSession *session;static dispatch_once_t onceToken;dispatch_once (&onceToken, Asession = NSURLSession sessionWithConfiguration :backgroundConfigObject delegate :self delegateQueue :nil;);return session;-(void )startBackground:( N

10、SMutableURLRequest *)request self .sesssionDataTask = self .urlSession uploadTaskWithStreamedRequest :request;self .sesssionDataTask resume ;-(void )stopUploadBackgroundself .sesssionDataTask cancel ;- (void )URLSession:( NSURLSession *)session dataTask:( NSURLSessionDataTask *)dataTask didReceiveDa

11、ta:( NSData *)data;if(data= nil)self .sessioinDelegaterequestUploadFinishDictionary :nil;return ;NSDictionary *dict = NSJSONSerializationJSONObjectWithData :data options :0 error :nil ;NSLog ("dict:%" ,dict);self .sessioinDelegate requestUploadFinishDictionary :dict;- (void )URLSession:( N

12、SURLSession *)session didBecomeInvalidWithError:( NSError *)error self .sessioinDelegate requestUploadFinishDictionary :nil; end上传 session 写好后,下面就可以使用这个 session 了,每个应用上传接口都不一样,但是 最终会调用上传, 我这里的方式是上传的信息全 部在 NSMutableURLRequest 中,NSMutableURLRequest 就大概说下NSMutableURLRequest*request= NSMutableURLRequest

13、 requestWithURL :s_url cachePolicy :NSURLRequestReloadIgnoringLocalCacheD ata timeoutInterval :CONNECT_TIMEOUT ;request setHTTPBody :data;request setHTTPMethod :"PUT" ;s_url :上传的接口 url,如 CONNECT_TIMEOUT :超时时间,如: 60data:将要上传的nsdata数据上传完成后回调方法:-(void)requestUploadFinishDictionary:( NSDiction

14、ary *)dictionary/处理逻辑5.很多上传逻辑中并不是仅仅包含上传文件的 业务,也有很多普通的网络请求, 我们来说说如 何把普通的网络请求也和 urlsession 方式处理, (SeesionConnection.h, SeesionConnection.m)/ SeesionConnection.h #import <Foundation/Foundation.h>protocol SeesionConnectionDelegate < NSObject >-(void )requestSeesionConnectionDictionary:( NSDi

15、ctionary *)dictionary;endinterface SeesionConnection : NSObjectproperty (nonatomic , strong ) NSURLSession *urlSession;property (nonatomic , strong ) NSURLSessionDownloadTask *sesssionDataTask;property (nonatomic , weak ) id<SeesionConnectionDelegate > sessioinDelegate;-(void )startBackground:

16、( NSMutableURLRequest *)request;-(void )stopDownBackground;end/ SeesionConnection.m#import "SeesionConnection.h"implementation SeesionConnection synthesize urlSession,sesssionDataTask,sessioinDelegate;-(NSURLSession *)urlSessionstatic NSURLSession *session; static dispatch_once_t onceToken

17、;dispatch_once (&onceToken, Asession = NSURLSession sessionWithConfiguration :backgroundConfigObject delegate :self delegateQueue :nil;);return session;-(void )startBackground:( NSMutableURLRequest self .sesssionDataTask = self .urlSession downloadTaskWithRequest :request;self .sesssionDataTask

18、resume ; -(void )stopDownBackgroundself .sesssionDataTask cancel ;*)requestNSURL- (void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:( *)locationNSFileManager *fileManager = NSFileManager defaultManager ;NSData *data = NSData d

19、ataWithContentsOfURL :location;if(data= nil)self .sessioinDelegate requestSeesionConnectionDictionary :nil;NSError *error;fileManager removeItemAtURL :location error :&error;NSLog ("error:%" ,error); return ;NSDictionary *dict = NSJSONSerialization JSONObjectWithData :data options :0 e

20、rror :nil ;NSLog ("dict:%" ,dict);self .sessioinDelegate requestSeesionConnectionDictionary :dict;NSError *error;fileManager removeItemAtURL :location error :&error; NSLog ("error:%" ,error);- (void )URLSession:( NSURLSession *)session didBecomeInvalidWithError:( NSError *)er

21、rorself .sessioinDelegate requestSeesionConnectionDictionary :nil;end网路请求的 session 写好后就是调用了SessionVerifyBackground *sessioinVerifyBackground SessionVerifyBackground alloc init ;sessioinVerifyBackground setSessioinDelegate :self ;类,sessioinVerifyBackground startBackground :request;request :自己去创建吧, NS

22、MutableURLRequest-(void )requestSeesionConnectionDictionary:( NSDictionary *)dictionary/这里处理逻辑6.下载 session 的代码( DownSessionBackground.h, DownSessionBackground.m )/ DownSessionBackground.h#import <Foundation/Foundation.h>interface DownSessionBackground :NSObject <NSURLSessionDownloadDelegate

23、 >property (nonatomic , assign ) BOOL isBackGround;property (nonatomic , strong , readonly ) NSURLSession *urlSession;property (nonatomic , strong ) NSURLSessionDownloadTask *downloadTask;-(id )init;-(void )startDownBackground;-(void )stopDownBackground;end/ DownSessionBackground.m#import "D

24、ownSessionBackground.h"implementation DownSessionBackgroundsynthesize isBackGround,urlSession,downloadTask;-(id )initstatic DownSessionBackground *background;static dispatch_once_t onceToken;dispatch_once (&onceToken, Abackground = super init;);return background; - ( NSURLSe s s i o n *)url

25、Sessionstatic NSURLSession *backgroundSession = nil; static dispatch_once_t onceToken;dispatch_once (&onceToken, ANSURLSessionConfiguration *config = NSURLSessionConfiguration backgroundSessionConfiguration :"com.shinobicontrols. BackgroundDownload.BackgroundSessions" ;backgroundSessio

26、n = NSURLSession sessionWithConfiguration :config delegate :self delegateQueue :nil;);return backgroundSession; -(void )startDownBackgroundif(self.isBackGround )NSString *url =" phone/conceptual/iphoneosprogrammingguide/iphoneapp programmingguide.pdf" ;NSURLRequest *request = NSURLRequest

27、requestWithURL :NSURL URLWithString :url;self .downloadTask = self .urlSession downloadTaskWithRequest :request;/ Start the downloadself .downloadTask resume ;-(void )stopDownBackgroundself .downloadTask cancel ;#pragma mark NSURLSessionDelegate- (void )URLSession:( NSURLSession *)session downloadTa

28、sk:( NSURLSessionDownloadTask *)downloadTask didWriteData:( int64_t )bytesWritten totalBytesWritten:( int64_t )totalBytesWrittentotalBytesExpectedToWrite:( int64_t )totalBytesExpectedTo Writedouble currentProgress = totalBytesWritten /(double )totalBytesExpectedToWrite;NSString *percentStr = NSNumbe

29、rFormatter localizedStringFromNumber :NSNumber numberWithDouble :currentProgress numberStyle :NSNumberFormatterPercentStyle ;NSLog ("当前下载 %" ,percentStr);- (void )URLSession:( NSURLSession *)session downloadTask:( NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:( NSURL *)

30、locationNSLog (" 下载成功 ");NSLog ("下载的文件路径: %" ,location);NSError *error;NSFileManager *fileManager = NSFileManager defaultManager ;NSString *documentDir = self getFMCachePath ;NSString *destinationFilename = downloadTask. originalRequest .URL .lastPathComponent ;NSArray *array=des

31、tinationFilename componentsSeparatedByString :"/" ;NSString *createPath = NSString stringWithFormat :"%" ,documentDir;self CreatePath :createPath;NSString *savedPath = NSString stringWithFormat :"%/%" ,createPath,array lastObject ;NSURL *destinationURL = NSURL fileURLWithPath :savedPath;if (fileManager fileExistsAtPath :des

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论