国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

RestKit,一個(gè)用于更好支持RESTful風(fēng)格服務(wù)器接口的iOS庫

2019-11-14 18:20:12
字體:
供稿:網(wǎng)友

簡介

RestKit 是一個(gè)用于更好支持RESTful風(fēng)格服務(wù)器接口的iOS庫,可直接將聯(lián)網(wǎng)獲取的json/xml數(shù)據(jù)轉(zhuǎn)換為iOS對象.

  • 項(xiàng)目主頁: RestKit
  • 最新示例: 點(diǎn)擊下載
  • 注意: 如果無法直接運(yùn)行示例根目錄的工程,可嘗試分別運(yùn)行 Examples 文件夾下的各個(gè)子工程,此時(shí)你需要給每個(gè)子工程都通過 CocoaPods 安裝一次 RestKit.

快速入門

使用環(huán)境

  • ARC
  • iOS 5.1.1 +

安裝

通過 CocoaPods 安裝

pod 'RestKit'# 測試和搜索是可選的組件pod 'RestKit/Testing'pod 'RestKit/Search'

使用

在需要的地方,引入頭文件:

/* 如果使用CoreData,一定要在引入RestKit前引入CoreData.RestKit中有一些預(yù)編譯宏是基于CoreData是否已經(jīng)引入;不提前引入CoreData,RestKit中CoreData相關(guān)的功能就無法正常使用. */#import <CoreData/CoreData.h>#import <RestKit/RestKit.h>/* Testing 和 Search 是可選的. */#import <RestKit/Testing.h>#import <RestKit/Search.h>

以下示例展示了RestKit的基本用法,涉及到網(wǎng)絡(luò)請求的部分已轉(zhuǎn)由iOS122的測試服務(wù)器提供模擬數(shù)據(jù).示例代碼復(fù)制到Xcode中,可直接執(zhí)行.建議自己新建工程,通過CocoaPods安裝RestKit測試.

對象請求

/** *  定義數(shù)據(jù)模型: Article */@interface Article : NSObject@PRoperty (nonatomic, copy) NSString * title;@property (nonatomic, copy) NSString * author;@property (nonatomic, copy) NSString * body;@end
// 從/vitural/articles/1234.json獲取一篇文章的信息,并把它映射到一個(gè)數(shù)據(jù)模型對象中.// JSON 內(nèi)容: {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];[mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任何 2xx 狀態(tài).RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes];    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dev-test.ios122.com/vitural/articles/1234.json"]];RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {    Article *article = [result firstObject];    NSLog(@"Mapped the article: %@", article);} failure:^(RKObjectRequestOperation *operation, NSError *error) {    NSLog(@"Failed with error: %@", [error localizedDescription]);}];[operation start];

管理對象請求

/* 需要額外引入頭文件:#import "RKManagedObjectRequestOperation.h". */    // 從 /vitural/articles/888.json 獲取文章和文章標(biāo)簽,并存放到Core Data實(shí)體中.// JSON  數(shù)據(jù)類似: {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!", "categories": [{"id": 1, "name": "Core Data"]}NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];NSError *error = nil;BOOL success = RKEnsureDirectoryExistsAtPath(RKapplicationDataDirectory(), &error);if (! success) {    RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);}    // 如果改了實(shí)體結(jié)構(gòu),注意刪除手機(jī)或模擬器對應(yīng)路徑的數(shù)據(jù)庫// 文章和標(biāo)簽,要設(shè)置 1 對 多的關(guān)聯(lián)!    NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"RestKit.sqlite"]; // 此處要和自己的CoreData數(shù)據(jù)庫的名字一致.NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];if (! persistentStore) {    RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);}[managedObjectStore createManagedObjectContexts];    /* 要在Core Data中預(yù)定義相關(guān)實(shí)體. */RKEntityMapping *categoryMapping = [RKEntityMapping mappingForEntityForName:@"Category" inManagedObjectStore:managedObjectStore];[categoryMapping addAttributeMappingsFromDictionary:@{ @"id": @"categoryID", @"name": @"name" }];RKEntityMapping *articleMapping = [RKEntityMapping mappingForEntityForName:@"Article" inManagedObjectStore:managedObjectStore];[articleMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"categories" toKeyPath:@"categories" withMapping:categoryMapping]];    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任何 2xx的狀態(tài)碼RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes];    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dev-test.ios122.com/vitural/articles/888.json"]];    RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];operation.managedObjectContext = managedObjectStore.mainQueueManagedObjectContext;operation.managedObjectCache = managedObjectStore.managedObjectCache;[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {    NSLog(@"Mapped the article: %@", [result firstObject]);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {    NSLog(@"Failed with error: %@", [error localizedDescription]);}];NSOperationQueue *operationQueue = [NSOperationQueue new];[operationQueue addOperation:operation];

把網(wǎng)絡(luò)請求的錯(cuò)誤信息映射一個(gè)到 NSError

// 獲取 /vitural/articles/error.json,返回報(bào)頭 422 (Unprocessable Entity)// JSON 內(nèi)容: {"errors": "Some Error Has Occurred"}// 你可以將錯(cuò)誤映射到任何類,但是通常使用`RKErrorMessage`就夠了.RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];//  包含錯(cuò)誤信息的鍵對應(yīng)的值,映射到iOS類的錯(cuò)誤信息相關(guān)的屬性中.[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"errorMessage"]];NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError);// 任意報(bào)頭狀態(tài)碼為 4xx 的返回值.RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"errors" statusCodes:statusCodes];NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dev-test.ios122.com/vitural/articles/error.json"]];RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@ [errorDescriptor]];[operation setCompletionBlockWithSuccess:nil failure:^(RKObjectRequestOperation *operation, NSError *error) {    // 映射到的iOS錯(cuò)誤類的`description`方法用來作為localizedDescription的值    NSLog(@"Loaded this error: %@", [error localizedDescription]);        // 你可以通過`NSError`的`userInfo`獲取映射后的iOS類的對象.    RKErrorMessage *errorMessage =  [[error.userInfo objectForKey:RKObjectMapperErrorObjectsKey] firstObject];        NSLog(@"%@", errorMessage);}];[operation start];

在對象管理器上集中配置.

// 設(shè)置文章或請求出錯(cuò)時(shí)的響應(yīng)描述.// 成功時(shí)的JSON類似于: {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];[mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任意 2xx 狀態(tài)碼.RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes];// 出錯(cuò)時(shí)返回的JSON類似: {"errors": "Some Error Has Occurred"}RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];// 包含錯(cuò)誤信息的鍵對應(yīng)的值,映射到iOS類的錯(cuò)誤信息相關(guān)的屬性中.[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"errorMessage"]];NSIndexSet *errorStatusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError);// 任意報(bào)頭狀態(tài)碼為 4xx 的返回值.RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"errors" statusCodes:errorStatusCodes];// 把響應(yīng)描述添加到管理器上.RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];[manager addResponseDescriptorsFromArray:@[articleDescriptor, errorDescriptor ]];// 注意,此處所用的接口已在服務(wù)器端設(shè)置為隨機(jī)返回正確或錯(cuò)誤的信息,以便于測試.[manager getObject: nil path:@"/vitural/articles/555.json" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {    // 處理請求成功獲取的文章.    Article *article = [mappingResult firstObject];    NSLog(@"Mapped the article: %@", article);} failure:^(RKObjectRequestOperation *operation, NSError *error) {    // 處理錯(cuò)誤信息.    NSLog(@"%@", error.localizedDescription);}];

在對象管理器中整合CoreData

/* 配置管理器. */RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];[RKObjectManager setSharedManager: manager];    /* 將管理器與CoreData整合到一起. */NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];    NSError * error = nil;    BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);if (! success) {    RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);}NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"RestKit.sqlite"]; // 此處要和自己的CoreData數(shù)據(jù)庫的名字一致.NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];if (! persistentStore) {    RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);}[managedObjectStore createManagedObjectContexts];    manager.managedObjectStore = managedObjectStore;    /* 將網(wǎng)絡(luò)請求的數(shù)據(jù)存儲到CoreData, 要在Core Data中預(yù)定義相關(guān)實(shí)體. */RKEntityMapping *categoryMapping = [RKEntityMapping mappingForEntityForName:@"Category" inManagedObjectStore:manager.managedObjectStore];[categoryMapping addAttributeMappingsFromDictionary:@{ @"id": @"categoryID", @"name": @"name" }];RKEntityMapping *articleMapping = [RKEntityMapping mappingForEntityForName:@"Article" inManagedObjectStore:manager.managedObjectStore];[articleMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];[articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"categories" toKeyPath:@"categories" withMapping:categoryMapping]];    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任何 2xx的狀態(tài)碼RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes];    [manager addResponseDescriptor: responseDescriptor];[manager getObject: nil path:@"/vitural/articles/888.json" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {    // 處理請求成功獲取的文章.    NSLog(@"Mapped the article: %@", [mappingResult firstObject]);} failure:^(RKObjectRequestOperation *operation, NSError *error) {    // 處理錯(cuò)誤信息.    NSLog(@"%@", error.localizedDescription);}];

從一個(gè)地址獲取一組數(shù)據(jù)

    // 設(shè)置文章或請求出錯(cuò)時(shí)的響應(yīng)描述.    // 成功時(shí)的JSON類似于: [{"article":{"title":"My Article 1","author":"Blake 1","body":"Very cool!! 1"}},{"article":{"title":"My Article 2","author":"Blake 2","body":"Very cool!! 2"}},{"article":{"title":"My Article 3","author":"Blake 3","body":"Very cool!! 3"}},{"article":{"title":"My Article 4","author":"Blake 4","body":"Very cool!! 4"}}]    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];    [mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任意 2xx 狀態(tài)碼.        RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles" keyPath:@"article" statusCodes:statusCodes];        // 出錯(cuò)時(shí)返回的JSON類似: {"errors": "Some Error Has Occurred"}    RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];    // 包含錯(cuò)誤信息的鍵對應(yīng)的值,映射到iOS類的錯(cuò)誤信息相關(guān)的屬性中.        [errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"errorMessage"]];    NSIndexSet *errorStatusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError);    // 任意報(bào)頭狀態(tài)碼為 4xx 的返回值.    RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"errors" statusCodes:errorStatusCodes];        // 把響應(yīng)描述添加到管理器上.    RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];    [manager addResponseDescriptorsFromArray:@[articleDescriptor, errorDescriptor ]];    [manager getObjectsAtPath:@"/vitural/articles" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {        // 處理請求成功獲取的文章.        NSArray * articles = [mappingResult array];                [articles enumerateObjectsUsingBlock:^(Article * article, NSUInteger idx, BOOL *stop) {            NSLog(@"Mapped the article: %@", article);        }];            } failure:^(RKObjectRequestOperation *operation, NSError *error) {        // 處理錯(cuò)誤信息.        NSLog(@"%@", error.localizedDescription);    }];

使用隊(duì)列管理對象請求

RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dev-test.ios122.com/vitural/articles/1234.json"]];    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];    [mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任意 2xx 狀態(tài)碼.    RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/1234.json" keyPath:@"article" statusCodes:statusCodes];RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[articleDescriptor]];[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {    Article *article = [result firstObject];    NSLog(@"Mapped the article: %@", article);} failure:^(RKObjectRequestOperation *operation, NSError *error) {    NSLog(@"Failed with error: %@", [error localizedDescription]);}];[manager enqueueObjectRequestOperation:operation]; // 有了這句,就不需要再調(diào)用[operation start] 來發(fā)起請求了.[manager cancelAllObjectRequestOperationsWithMethod:RKRequestMethodAny matchingPathPattern:@"/vitural/articles/:articleID//.json"];

新建,更新 與 刪除對象.

RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[Article class]];[responseMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任何 2xx 狀態(tài)碼RKResponseDescriptor *articlesDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:@"/vitural/articles" keyPath:@"article" statusCodes:statusCodes];RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:id" keyPath:@"article" statusCodes:statusCodes];RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];[requestMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];// 將 Article 序列化為NSMutableDictionary ,并以 `article`為鍵.RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[Article class] rootKeyPath:@"article" method:RKRequestMethodAny];RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];[manager addRequestDescriptor:requestDescriptor];[manager addResponseDescriptor:articlesDescriptor];[manager addResponseDescriptor:articleDescriptor];Article *article = [Article new];article.title = @"Introduction to RestKit";article.body = @"This is some text.";article.author = @"Blake";// POST 創(chuàng)建對象.[manager postObject: article path:@"/vitural/articles" parameters: nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {    /* 這個(gè)接口服務(wù)器的暫時(shí)的邏輯是:把POST過去的數(shù)據(jù),原樣返回,以確認(rèn)POST請求成功.*/        Article *article = [mappingResult firstObject];        NSLog(@"Mapped the article: %@", article);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {        NSLog(@"Failed with error: %@", [error localizedDescription]);    }];// PACTH 更新對象.article.body = @"New Body";[manager patchObject:article path:@"/vitural/articles/1234" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {    /* 這個(gè)接口服務(wù)器的暫時(shí)的邏輯是:把PACTH過去的數(shù)據(jù),原樣返回,以確認(rèn)PATCH請求成功.*/    Article *article = [mappingResult firstObject];    NSLog(@"Mapped the article: %@", article);} failure:^(RKObjectRequestOperation *operation, NSError *error) {    NSLog(@"Failed with error: %@", [error localizedDescription]);}];// DELETE 刪除對象./* DELETE 操作會影響上面兩個(gè)接口,最好單獨(dú)操作. *///    [manager deleteObject:article path:@"/vitural/articles/1234" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {//        /* 這個(gè)接口服務(wù)器的暫時(shí)的邏輯是:把DELTE過去的數(shù)據(jù),article字段設(shè)為空,以確認(rèn)DELETE請求成功.*/////        Article *article = [mappingResult firstObject];//        NSLog(@"Mapped the article: %@", article);//    } failure:^(RKObjectRequestOperation *operation, NSError *error) {//        NSLog(@"Failed with error: %@", [error localizedDescription]);//    }];

日志設(shè)置

//  記錄所有HTTP請求的請求和相應(yīng).RKLogConfigureByName("RestKit/Network", RKLogLevelTrace);    // 記錄Core Data 的調(diào)試信息.RKLogConfigureByName("RestKit/CoreData", RKLogLevelDebug);    // 記錄block的調(diào)用.RKLogWithLevelWhileExecutingBlock(RKLogLevelTrace, ^{    // 自定義日志信息.    });

配置路由

路由,提供了URL無關(guān)的網(wǎng)絡(luò)請求調(diào)用方式.它是為了在類/某個(gè)名字/某個(gè)實(shí)體聯(lián)系 與 某個(gè)URL建立某種關(guān)聯(lián),以便再操作某個(gè)對象時(shí),只需要告訴RestKit這個(gè)對象本身的某些屬性就可以直接發(fā)送網(wǎng)絡(luò)請求,而不必每次都去手動拼接 URL.

  /* 設(shè)置共享的對象管理器. */    RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];    [RKObjectManager setSharedManager: manager];        /* 將管理器與CoreData整合到一起. */    NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];    RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];        NSError * error = nil;        BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);    if (! success) {        RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);    }    NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"RestKit.sqlite"]; // 此處要和自己的CoreData數(shù)據(jù)庫的名字一致.    NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];    if (! persistentStore) {        RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);    }    [managedObjectStore createManagedObjectContexts];    manager.managedObjectStore = managedObjectStore;        // 響應(yīng)描述,總是必須的.    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];        [mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];        NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任意 2xx 狀態(tài)碼.        RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes]; // articleID 應(yīng)為 Article 類的一個(gè)屬性.    [manager addResponseDescriptor: articleDescriptor];        /* 類的路由.配置后,操作某個(gè)類時(shí),會自動向這個(gè)類對應(yīng)的地址發(fā)送請求. */    [manager.router.routeSet addRoute:[RKRoute routeWithClass:[Article class] pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodGET]];        /*  發(fā)起請求. */    Article * article = [[Article alloc] init];    article.articleID = @"888"; // articleId 屬性必須給,以拼接地址路由中缺少的部分.        // 因?yàn)榕渲昧寺酚?所以此處不必再傳 path 參數(shù).    [manager getObject: article path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {        // 處理請求成功獲取的文章.        NSLog(@"Mapped the article: %@", [mappingResult firstObject]);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {        // 處理錯(cuò)誤信息.        NSLog(@"%@", error.localizedDescription);    }];        /* 關(guān)系路由: 使用CoreData實(shí)體間關(guān)系命名的路由.*/    /* 僅在測試CoreData關(guān)系路由時(shí),才需要把下面一段的代碼注釋打開. *///    RKEntityMapping *categoryMapping = [RKEntityMapping mappingForEntityForName:@"Category" inManagedObjectStore:manager.managedObjectStore];//    //    [categoryMapping addAttributeMappingsFromDictionary:@{ @"id": @"categoryID", @"name": @"name" }];//    RKEntityMapping *articleMapping = [RKEntityMapping mappingForEntityForName:@"Article" inManagedObjectStore:manager.managedObjectStore];//    [articleMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];//    [articleMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"categories" toKeyPath:@"categories" withMapping:categoryMapping]];//    //    NSIndexSet *coreDataStatusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任何 2xx的狀態(tài)碼//    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:articleMapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:coreDataStatusCodes];//    //    [manager addResponseDescriptor: responseDescriptor];        [manager.router.routeSet addRoute:[RKRoute routeWithRelationshipName:@"categories" objectClass:[Article class] pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodGET]];        [manager getObjectsAtPathForRelationship:@"categories" ofObject:article parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {                // 處理請求成功獲取的文章.        NSLog(@"Mapped the article: %@", [mappingResult firstObject]);            } failure:^(RKObjectRequestOperation *operation, NSError *error) {                // 處理錯(cuò)誤信息.        NSLog(@"%@", error.localizedDescription);    }];    /* 被命名的路由,可以根據(jù)路由名字發(fā)起相關(guān)請求. */    [manager.router.routeSet addRoute:[RKRoute routeWithName:@"article_review" pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodGET]];        [manager getObjectsAtPathForRouteNamed: @"article_review" object:article parameters: nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {        // 處理請求成功獲取的文章.        NSLog(@"Mapped the article: %@", [mappingResult firstObject]);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {        // 處理錯(cuò)誤信息.        NSLog(@"%@", error.localizedDescription);    }];

POST 新建一個(gè)含有文件附件的對象.

  RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];    [RKObjectManager setSharedManager: manager];        /* 響應(yīng)描述,總是必須的. */    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];        [mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];        NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // 任意 2xx 狀態(tài)碼.        RKResponseDescriptor *articleDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/vitural/articles/:articleID" keyPath:@"article" statusCodes:statusCodes]; // articleID 應(yīng)為 Article 類的一個(gè)屬性.    [manager addResponseDescriptor: articleDescriptor];        /* 類的路由.配置后,操作某個(gè)類時(shí),會自動向這個(gè)類對應(yīng)的地址發(fā)送請求. */    [manager.router.routeSet addRoute:[RKRoute routeWithClass:[Article class] pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodPOST]];        Article *article = [[Article alloc]init];    article.articleID = @"666";        UIImage *image = [UIImage imageNamed:@"test.jpg"]; // 工程中要確實(shí)存在一張名為 test.jpg 的照片.        // 序列化對象屬性,以添加附件.    NSMutableURLRequest *request = [[RKObjectManager sharedManager] multipartFormRequestWithObject:article method:RKRequestMethodPOST path:nil parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {        [formData appendPartWithFileData:UIImagePNGRepresentation(image)                                    name:@"myImg" // 這個(gè)字段要和服務(wù)器取文件的字段一致.                                fileName:@"photo.jpg"                                mimeType:@"image/jpeg"];    }];        RKObjectRequestOperation *operation = [[RKObjectManager sharedManager] objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {        /* 服務(wù)器端接口目前自定義的邏輯是: 成功后,會返回圖片上傳后的服務(wù)器地址. */        NSLog(@"Mapped the article: %@", [mappingResult firstObject]);    } failure:^(RKObjectRequestOperation *operation, NSError *error) {        NSLog(@"%@", error.localizedDescription);    }];        [[RKObjectManager sharedManager] enqueueObjectRequestOperation:operation]; // 注意:要用enqueued,不要使用 started方法.

以隊(duì)列方式批量處理對像請求.

 	RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://dev-test.ios122.com"]];        Article * articleA = [[Article alloc] init];    articleA.articleID = @"888";        Article * articleB = [[Article alloc] init];    articleB.articleID = @"1234";        Article * articleC = [[Article alloc] init];    articleC.articleID = @"555";        /* 以隊(duì)列方式,發(fā)送多個(gè)請求. */        [manager.router.routeSet addRoute:[RKRoute routeWithClass:[Article class] pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodGET]];        RKRoute * route = [RKRoute routeWithClass:[Article class] pathPattern:@"/vitural/articles/:articleID//.json" method:RKRequestMethodPOST];    [manager enqueueBatchOfObjectRequestOperationsWithRoute:route                                                    objects:@[articleA, articleB, articleC]                                                   progress:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {                                                       NSLog(@"完成了 %lu 個(gè)操作", (unsigned long)numberOfFinishedOperations);                                                   } completion:^ (NSArray *operations) {                                                       NSLog(@"所有的文章都已獲取!");                                                   }];

制作一個(gè)種子數(shù)據(jù)庫.

可以將一個(gè)JSON文件轉(zhuǎn)化為一個(gè)數(shù)據(jù)庫,用于初始化應(yīng)用.

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];    RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];    NSError *error = nil;    BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);    if (! success) {        RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);    }        NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"RestKit.sqlite"]; // 此處要和自己的CoreData數(shù)據(jù)庫的名字一致.    NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];    if (! persistentStore) {        RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);    }    [managedObjectStore createManagedObjectContexts];        RKEntityMapping *articleMapping = [RKEntityMapping mappingForEntityForName:@"Article" inManagedObjectStore:managedObjectStore];    [articleMapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];        NSString *seedPath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"MySeedDatabase.sqlite"]; // 這個(gè)數(shù)據(jù)庫文件不必存在,用來充當(dāng)應(yīng)用的初始數(shù)據(jù)庫.    RKManagedObjectImporter *importer = [[RKManagedObjectImporter alloc] initWithManagedObjectModel:managedObjectStore.managedObjectModel storePath:seedPath];        //  使用 RKEntityMapping 從工程文件 "articles.json" 導(dǎo)入數(shù)據(jù).    // JSON 類似于: {"articles": [ {"title": "Article 1", "body": "Text", "author": "Blake" ]}    error = nil;        NSBundle *mainBundle = [NSBundle mainBundle];    [importer importObjectsFromItemAtPath:[mainBundle pathForResource:@"articles" ofType:@"json"] // 工程中要有這個(gè)文件.                              withMapping:articleMapping                                  keyPath:@"articles"                                    error:&error];        success = [importer finishImporting:&error];        if (success) {        [importer logSeedingInfo];    }

給實(shí)體添加索引并檢索

// 要額外添加頭文件: #import <RestKit/Search.h>NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];NSError *error = nil;BOOL success = RKEnsureDirectoryExistsAtPath(RKApplicationDataDirectory(), &error);if (! success) {    RKLogError(@"Failed to create Application Data Directory at path '%@': %@", RKApplicationDataDirectory(), error);}NSString *path = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"Store.sqlite"];NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:path fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];if (! persistentStore) {    RKLogError(@"Failed adding persistent store at path '%@': %@", path, error);}[managedObjectStore createManagedObjectContexts];[managedObjectStore addSearchIndexingToEntityForName:@"Article" onAttributes:@[ @"title", @"body" ]];[managedObjectStore addInMemoryPersistentStore:nil];[managedObjectStore createManagedObjectContexts];[managedObjectStore startIndexingPersistentStoreManagedObjectContext];Article *article1 = [NSEntityDescription insertNewObjectForEntityForName:@"Article" inManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext];article1.title = @"First Article";article1.body = "This should match search";Article *article2 = [NSEntityDescription insertNewObjectForEntityForName:@"Article" inManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext];article2.title = @"Second Article";article2.body = "Does not";BOOL success = [managedObjectStore.mainQueueManagedObjectContext saveToPersistentStore:nil];RKSearchPredicate *predicate = [RKSearchPredicate searchPredicateWithText:@"Match" type:NSAndPredicateType];NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Article"];fetchRequest.predicate = predicate;// Contains article1 due to body text containing 'match'NSArray *matches = [managedObjectStore.mainQueueManagedObjectContext executeFetchRequest:fetchRequest error:nil];NSLog(@"Found the matching articles: %@", matches);

對映射進(jìn)行單元測試

// JSON looks like {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];[mapping addAttributeMappingsFromArray:@[@"title", @"author", @"body"]];NSDictionary *article = @{ @"article": @{ @"title": @"My Title", @"body": @"The article body", @"author": @"Blake" } };RKMappingTest *mappingTest = [[RKMappingTest alloc] initWithMapping:mapping sourceObject:article destinationObject:nil];[mappingTest expectMappingFromKeyPath:@"title" toKeyPath:@"title" value:@"My Title"];[mappingTest performMapping];[mappingTest verify];

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 江阴市| 永福县| 涿鹿县| 遵化市| 西昌市| 莆田市| 阳谷县| 深圳市| 五华县| 滁州市| 开鲁县| 喜德县| 宁津县| 巨鹿县| 南阳市| 方山县| 昭平县| 加查县| 丰原市| 苍溪县| 宽城| 和静县| 东乡| 叶城县| 洛隆县| 邵东县| 广饶县| 溧水县| 龙陵县| 罗山县| 高碑店市| 鄂托克旗| 类乌齐县| 农安县| 洛扎县| 巨鹿县| 富平县| 兴仁县| 西畴县| 平武县| 青川县|