Open Platform: stackmob for iOS

Source: Internet
Author: User

Introduction:

StackmobIs a lightweightBaasThe mobile backend cloud storage platform provides powerful background cloud storage capabilities for mobile apps.Core DataBody, without changingCore
Data API
The usage isCore DataThis topic describes how to provide cloud storage capabilities.StackmobIn the IOS environment.

References:

1: stackmob Homepage

Https://www.stackmob.com/

2: stackmob iOS development documentation

Http://stackmob.github.io/stackmob-ios-sdk/

3: how to add back-end network service series for iOS apps and games

Http://blog.sina.com.cn/s/blog_4b55f6860101b991.html

4: Official stackmob SDK tutorials

Https://developer.stackmob.com/tutorials/ios

The temptation at introduced the entire process from registration to use of stackmob:

Http://www.csdn.net/article/2013-03-19/2814542-build-an-airbnb-clone/1

Installation:

Stackmob is open-source and its hosting address is as follows:

Https://github.com/stackmob/stackmob-ios-sdk

The first installation method isCocoapods.

Possible problems:

1: Solve the Problem of warning deployment after afnetworkkiting is installed. For details, refer to this article.

2: To solve the reachability class conflict, the Code is as follows:

3: connect stackmob to Amazon S3

Stackmob can store binary files only after connecting to Amazon S3.

This blog roughly introduces the S3 registration process, which can be slightly referenced:

Http://www.xieyidian.com/2692

Step 1: Go to Amazon Web services to register a developer account:

Https://aws.amazon.com/cn/

Step 2: Register and activate S3

Https://aws.amazon.com/cn/s3/

To register and activate S3, you need a credit card that supports foreign currency payment. MasterCard is recommended.

Enter the following information on the card Request page:

Type Selection: MasterCard

Credit card No.

The name of the cardholder in Chinese pinyin. (enter the name based on the credit card)

A us dollar fee will be deducted after successful purchase, and an email notification will be sent to activate the S3 service.

Now you have activated the S3 service and have the right to use it. If you are still prompted to register on the S3 console, It is a browser cache issue. Just clear it.

Step 3: Go to the S3 console and createBucketFor example:

Https://console.aws.amazon.com/s3

Region: select the country where the server is located. The tighter the server, the better. Japan.

Step 4: Use the official stackmob connection tutorial to complete the process:

Http://developer.stackmob.com/tutorials/dashboard/Adding-a-Binary-Field-to-Schemas

Note a field When configuring the link in the last step, as shown in:

That isS3 path aliasWhen the value of this field is set incorrectly, use the access link generated by it. The access result is always a medium error:

How can I set it correctly?S3 path alias?

First, you must understandS3 path aliasWhat is it for? It is a link address alias.

When we useStackmobAfter a binary file is uploaded successfully,StackmobAutomaticallyS3 path aliasThe given value automatically generates a Complete Binary Download link.

To verify the correctness of the download link, go to the S3 console and find an uploaded file to view its details, as shown in:

In the imageLinkAndStackmobCompare the generated links to see if they are different. If they are differentS3 path aliasThere must be a problem with the settings.

Which is correctS3 path aliasThe setting method should be:Http://s3-ap-northeast-1.amazonaws.com/musicpushtest/

The final S3 pricing address is as follows: (new user registration is free for 12 months ):

Http://aws.amazon.com/cn/pricing/s3/

Usage:

Disadvantages:

1: No binary file upload progress

Cause:Solution

2: crash may occur when multiple query requests and save requests are initiated,

Cause: stackmob stops working or even crash due to thread call disorder. Before using stackmob, familiarize yourself with GCD. Refer to this tutorial. This article is more comprehensive.

3: After the query and save request is initiated, it cannot be undone immediately. You must wait until the entire request is completed.

Cause:Solution

4: by default, the start index of a paging query must be set to a value greater than 0:

Cause: I estimate the internal bug of the code. I can fix it by commenting out the code and checking that it is greater than 0.

5: crash when a one-to-many object is written to a specified plist file when it is cached locally

Cause: nsdictionary's key is not caused by nsstring. The method of replacing the key-value pair with the source code is modified.

6: After the object level is expanded, the sub-object data cannot be obtained.

Cause:Solution

Key features:

I. About Binary File Upload

1. SetCore DataThe data model field is of the string type.

2. manually setStackmobOfSchemaThe corresponding fields are of the binary type.

3. Field Names andStackmobOf
Schema
The field names are as follows:Local core data: UsericonSchema: User_icon

4. If a local field corresponds to a binary field of the server, you must assign a value through the following code when uploading the server:

+ (NSString *)convertUploadWithPath:(NSString *)aPath withContentType:(NSString *)aContentType{    NSData *data = [NSData dataWithContentsOfFile:aPath];    if (data) {        NSString *dataString = [SMBinaryDataConversion stringForBinaryData:data name:[aPath lastPathComponent] contentType:aContentType];        return dataString;    }else    {        return @"file?";    }}

Note: Assignment in any other method is not allowed. Otherwise, a bug that cannot be understood will occur .(Special note)

To download a successfully uploaded binary file field, run the following code:

[[StackMobManager contextForCurrentThread] refreshObject:self.dmSongTyoe mergeChanges:YES];

But this only appliesNew ObjectEffect. If you areUpdate objectIf you use the above Code to refresh, it will change back to the value you modified previously.How can this problem be solved?

Ii. Data Cache Mechanism

StackmobThe Caching mechanism of is disabled by default. To enable this function, you must assign values to the following global variables:

SM_CACHE_ENABLED = YES;

After setting,StackmobA local file is automatically created.Core DataThe database automatically manages and caches data from the server.

There is an enumeration for the Data Query mechanism to determine the Data fetch method:

Typedef Enum {smcachepolicytrynetworkonly = 0, // retrieve smcachepolicytrycacheonly = 1 from the network only, // retrieve smcachepolicytrynetworkelsecache = 2 from the cache, // obtain from the network first, smcachepolicytrycacheelsenetwork = 3 cannot be obtained, // This has not been studied} smcachepolicy;

If you have changed the network environment of the device, you can use the following block to modify the Data Query mechanism:

SMClient *client = [[SMClient alloc] initWithAPIVersion:@"0" publicKey:@"XXXX"];SMCoreDataStore *coreDataStore = [client coreDataStoreWithManagedObjectModel:myModel];[client.session.networkMonitor setNetworkStatusChangeBlockWithCachePolicyReturn:^SMCachePolicy(SMNetworkStatus status) {        if (status == Reachable) {            return SMCachePolicyTryNetworkElseCache;        } else {            return SMCachePolicyTryCacheOnly;        }}];

When the app is started, determine the current network environment and set the Data Query mechanism:

if ([Reachability isEnable3G] || [Reachability isEnableWIFI]) {    [self.keyCoreDataStore setCachePolicy:SMCachePolicyTryNetworkElseCache];}else{    [self.keyCoreDataStore setCachePolicy:SMCachePolicyTryCacheOnly];}

Iii. saveonsuccess)

PairObjectAny addition, deletion, and modificationSaveonsuccessTo maintain data synchronization on the cloud.

It is quite easy to use, but some small details should be noted, otherwise it will be very tangled.

1. saveonsuccessIf the storage fails due to network issues or duplicate primary keys, the failed block is entered.

If you enter3, 4The failure block is left or right. It is ~~~~~ It ~ Ya's ~AppJustCrashNow, the slot... @ try @ catch cannot stop this crash.

The solution is to execute the code in the failed block.Core DataDelete the object to be saved in the context.

[StackMobManager contextForCurrentThread] deleteObject:obj];

This won't happen no matter how many times you clickCrashI think this isStackmobI am also a cainiao and cannot make comments on the design issues.

2. Updating passwords via this API is disabled for security reasons. Use the resetpassword API instead

This prompt is printed on the console to indicate that your current data storage request is restricted by the cloud terminal.

How do I trigger this?Error?

When I create a newUserObject, and save one moreFileObject.FileThe object depends onUserObject, that isFileThe object ownership isUserObject, but you did not log on when creating the user object.

In the authorization security mechanism, this save request even fails (even if the data has been saved to the cloud ).

The solution is not to save it to the cloud together, but to initiate it after the login is successful.FileObject Storage request.

4. Query (Executefetchrequest)

This function is used to query objects. Basically, it is similar to the coredata query function,StackmobTwo query request methods are provided.

One is to build a multi-threaded internal operation without getting stuck in the main thread and affecting the interface. After the operation is completed, the main thread will notify you:

However, there is a high probability that the entire SDK stops working when this request is initiated multiple times in a row. This is a serious problem and should be a stackmob bug,

The other method is not to build multithreading. If you execute the program directly, the main thread will be stuck before the result is returned, affecting the interface experience, however, we can use GCD to avoid the main thread blocking problem.

In this way, it seems that the bug caused by multiple request initiation can be avoided, at least not found for the time being.

There isParameter classNote that this class is also an important way to implement personalized queries,

It isSmrequestoptions

What is its use:

1: Do you want to refresh the token? Tryrefreshtoken

2: How to securely obtain data through htpps encryption? Issecure

3: How many times do I retry when the request network times out? Numberofretries

4: How many layers do I need to expand the returned data structure? (Up to three levels) setexpanddepth

5: I just want to return the data of several fields. restrictreturnedfieldsto

Summary:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.