iOS学习笔记-07必要知识

Posted by 蔡华的博客 on September 16, 2016

7.必要知识

7.1 APNS

  • 目前在8.0以后的推送需要以下几个步骤:

1.使用registerUserNotificationSettings: & registerForRemoteNotifications方法

```
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)]) {
     UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil];
     [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; 
     [[UIApplication sharedApplication] registerForRemoteNotifications];
}
 
```

关于registerForRemoteNotifications方法有以下说明,它会需要实现两个delegate方法,并且方法能够被执行的条件是通过registerUserNotificationSettings:方法成功注册用户的notification,或者enabled for Background App Refresh。

// Calling this will result in either application:didRegisterForRemoteNotificationsWithDeviceToken: or application:didFailToRegisterForRemoteNotificationsWithError: to be called on the application delegate. Note: these callbacks will be made only if the application has successfully registered for user notifications with registerUserNotificationSettings:, or if it is enabled for Background App Refresh

2.实现delegate方法:每个APP都不同,就不写了。

7.2 block tips

  • 多使用typedef来定义block,因为简洁、可复用、对于结构相同的block可以通过命名来区分。
  • 在定义API时多用handle block来降低代码分散程度。
  • 注意在使用block时循环引用对象
	
	#import "BlockHandle.h"
	#import <Foundation/Foundation.h>
	
	@interface BlockClass : NSObject
	
	@property (strong, nonatomic) NSData* localData;
	
	@property (strong, nonatomic) BlockHandle* bh;
	- (void)download;
	
	@end
	
	#import "BlockClass.h"
	
	@implementation BlockClass
	
	- (void)download
	{
	    //    BlockHandle* bh
	    self.bh = [[BlockHandle alloc] initWithUrl:@""];
	    [self.bh startDownloadwithcompletionHandleBlock:^(NSData* data) {
	        self.localData = data;
	        // 解除引用,打破保留环
	        self.bh = nil;
	    }];
	}
	
	- (void)dealloc
	{
	    NSLog(@"BlockClass dealloc");
	}
	
	@end
	
	```
	
#import <Foundation/Foundation.h>

typedef void (^completionHandleBlock)(NSData* data);

@interface BlockHandle : NSObject
@property (strong, nonatomic) NSString* url;
@property (strong, nonatomic) completionHandleBlock block;

- (id)initWithUrl:(NSString*)url;
- (void)startDownloadwithcompletionHandleBlock:(completionHandleBlock)block;

@end

#import "BlockHandle.h"

@implementation BlockHandle

- (id)initWithUrl:(NSString*)url
{
    self = [super init];
    if (self) {
        self.url = url;
    }
    return self;
}

- (void)startDownloadwithcompletionHandleBlock:(completionHandleBlock)block
{
    self.block = block;
    if (self.block != nil) {
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [NSThread sleepForTimeInterval:3];
                self.block(nil);
            });
        }
    }
}

- (void)dealloc
{
    NSLog(@"BlockHandle dealloc");
}

@end

```