【实战】从零开发鸿蒙5社交App:AGC全栈集成指南

引言
本文将带领您从零开始开发一个基于HarmonyOS 5的社交应用,并完整集成AppGallery Connect(AGC)的核心服务,包括认证、云数据库和云存储功能。通过本教程,您将掌握如何构建一个现代化、全栈式的HarmonyOS社交应用。

一、项目初始化

  1. 创建HarmonyOS 5项目
    使用DevEco Studio创建新项目,选择"Application" > "Empty Ability",配置如下:

Project Name: SocialHarmony
Bundle Name: com.example.socialharmony
Save Location: 选择您的项目路径
Compatible API Version: HarmonyOS 5.0
2. 配置AGC服务
在entry/build.gradle中添加依赖:

dependencies {
// AGC核心
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.9.0.300'
// 认证服务
implementation 'com.huawei.agconnect:agconnect-auth-harmony:1.9.0.300'
// 云数据库
implementation 'com.huawei.agconnect:agconnect-cloud-database-harmony:1.9.0.300'
// 云存储
implementation 'com.huawei.agconnect:agconnect-storage-harmony:1.9.0.300'
// 分析服务
implementation 'com.huawei.agconnect:agconnect-analytics-harmony:1.9.0.300'
}
二、用户认证集成

  1. 初始化认证服务
    在EntryAbility中初始化AGC认证:

import agconnect from '@hw-agconnect/api-harmony';
import '@hw-agconnect/auth-harmony';

export default class EntryAbility extends Ability {
onCreate(want, launchParam) {
// 初始化AGC
agconnect.instance().init(this.context);
}
}
2. 实现手机号登录
import agconnect from '@hw-agconnect/api-harmony';
import { AGCAuth } from '@hw-agconnect/auth-harmony';

async function phoneLogin(countryCode: string, phoneNumber: string, verifyCode: string) {
try {
// 创建凭证
const credential = AGCAuth.credentialWithVerifyCode(
countryCode,
phoneNumber,
"", // 密码,可为空
verifyCode
);

    // 登录
    const user = await agconnect.auth().signIn(credential);
    console.log('Login success:', user);
    return user;
} catch (error) {
    console.error('Login failed:', error);
    throw error;
}

}

// 发送验证码
async function sendVerifyCode(countryCode: string, phoneNumber: string) {
try {
await agconnect.auth().requestVerifyCode(phoneNumber, countryCode, {
action: AGCAuth.ACTION_REGISTERLOGIN, // 登录/注册操作
lang: 'zh_CN', // 语言
sendInterval: 30 // 发送间隔
});
console.log('Verify code sent successfully');
} catch (error) {
console.error('Failed to send verify code:', error);
throw error;
}
}
三、云数据库集成

  1. 创建数据模型
    // models/Post.ts
    export interface Post {
    id?: string; // 文档ID,自动生成
    userId: string;
    content: string;
    images?: string[];
    likes: number;
    comments: number;
    createTime: Date;
    updateTime: Date;
    }

// models/UserProfile.ts
export interface UserProfile {
id?: string;
userId: string;
nickname: string;
avatar: string;
bio?: string;
followers: number;
following: number;
createTime: Date;
updateTime: Date;
}
2. 初始化云数据库
import agconnect from '@hw-agconnect/api-harmony';
import { AGCCloudDB } from '@hw-agconnect/cloud-database-harmony';

// 初始化云数据库
const cloudDB = AGCCloudDB.getInstance(agconnect.instance());

// 创建对象类型
async function initObjectTypes() {
try {
await cloudDB.createObjectType({
objectTypeName: 'Post',
fields: {
userId: { isNull: false, isIndex: true },
content: { isNull: false },
images: { isArray: true },
likes: { isNull: false, defaultValue: 0 },
comments: { isNull: false, defaultValue: 0 },
createTime: { isNull: false },
updateTime: { isNull: false }
}
});

    await cloudDB.createObjectType({
        objectTypeName: 'UserProfile',
        fields: {
            userId: { isNull: false, isIndex: true, isUnique: true },
            nickname: { isNull: false },
            avatar: { isNull: false },
            bio: { isNull: true },
            followers: { isNull: false, defaultValue: 0 },
            following: { isNull: false, defaultValue: 0 },
            createTime: { isNull: false },
            updateTime: { isNull: false }
        }
    });
    
    console.log('Object types created successfully');
} catch (error) {
    console.error('Failed to create object types:', error);
}

}
3. 实现CRUD操作
// services/postService.ts
import { AGCCloudDB, AGCObject } from '@hw-agconnect/cloud-database-harmony';
import { Post } from '../models/Post';

const cloudDB = AGCCloudDB.getInstance(agconnect.instance());

export class PostService {
// 创建帖子
static async createPost(post: Post): Promise {
const now = new Date();
post.createTime = now;
post.updateTime = now;

    const postObject = new AGCObject('Post', post);
    const result = await cloudDB.insert(postObject);
    return result.getId();
}

// 获取用户帖子
static async getUserPosts(userId: string, page: number = 1, pageSize: number = 10): Promise<Post[]> {
    const query = AGCCloudDB.where('Post')
        .equalTo('userId', userId)
        .orderByDesc('createTime')
        .limit(pageSize)
        .offset((page - 1) * pageSize);
    
    const snapshot = await cloudDB.executeQuery(query);
    return snapshot.getObjects().map(obj => obj.toObject() as Post);
}

// 更新帖子
static async updatePost(postId: string, updates: Partial<Post>): Promise<void> {
    updates.updateTime = new Date();
    await cloudDB.update(new AGCObject('Post', { id: postId, ...updates }));
}

// 删除帖子
static async deletePost(postId: string): Promise<void> {
    await cloudDB.delete(new AGCObject('Post', { id: postId }));
}

}
四、云存储集成

  1. 文件上传服务
    // services/storageService.ts
    import { AGCStorage } from '@hw-agconnect/storage-harmony';
    import agconnect from '@hw-agconnect/api-harmony';

const storage = AGCStorage.getInstance(agconnect.instance());

export class StorageService {
// 上传用户头像
static async uploadAvatar(userId: string, fileUri: string): Promise {
const storagePath = avatars/${userId}/${Date.now()}.jpg;
const reference = storage.reference(storagePath);

    try {
        await reference.putFile(fileUri);
        return await reference.getDownloadURL();
    } catch (error) {
        console.error('Failed to upload avatar:', error);
        throw error;
    }
}

// 上传帖子图片
static async uploadPostImage(userId: string, postId: string, fileUri: string): Promise<string> {
    const storagePath = `posts/${userId}/${postId}/${Date.now()}.jpg`;
    const reference = storage.reference(storagePath);
    
    try {
        await reference.putFile(fileUri);
        return await reference.getDownloadURL();
    } catch (error) {
        console.error('Failed to upload post image:', error);
        throw error;
    }
}

// 删除文件
static async deleteFile(fileUrl: string): Promise<void> {
    const reference = storage.referenceFromUrl(fileUrl);
    await reference.delete();
}

}
2. 图片上传组件实现
// components/ImageUploader.ts
import { StorageService } from '../services/storageService';

@Entry
@Component
struct ImageUploader {
@State previewUris: string[] = []
@State isUploading: boolean = false

async onFileSelect(files: Array<string>) {
    this.isUploading = true;
    
    try {
        const userId = agconnect.auth().currentUser?.uid;
        if (!userId) throw new Error('User not logged in');
        
        const uploadPromises = files.map(fileUri => 
            StorageService.uploadPostImage(userId, 'temp', fileUri)
        );
        
        const urls = await Promise.all(uploadPromises);
        this.previewUris = [...this.previewUris, ...urls];
    } catch (error) {
        console.error('Upload failed:', error);
    } finally {
        this.isUploading = false;
    }
}

build() {
    Column() {
        if (this.isUploading) {
            Progress({ value: 0, total: 100 })
                .width('80%')
                .margin(10)
        }
        
        Button('选择图片')
            .onClick(() => {
                // 调用系统文件选择器
                // 实际实现需要调用HarmonyOS的文件选择API
            })
        
        Flex({ wrap: FlexWrap.Wrap }) {
            ForEach(this.previewUris, (uri) => {
                Image(uri)
                    .width(80)
                    .height(80)
                    .margin(5)
            })
        }
    }
}

}
五、社交功能实现

  1. 用户主页实现
    // pages/UserProfilePage.ts
    import { PostService } from '../services/postService';
    import { UserProfileService } from '../services/userProfileService';

@Entry
@Component
struct UserProfilePage {
@State userId: string = ''
@State userProfile: UserProfile | null = null
@State posts: Post[] = []
@State isLoading: boolean = true

async onPageShow() {
    this.isLoading = true;
    
    try {
        // 获取用户资料
        this.userProfile = await UserProfileService.getUserProfile(this.userId);
        
        // 获取用户帖子
        this.posts = await PostService.getUserPosts(this.userId);
    } catch (error) {
        console.error('Failed to load profile:', error);
    } finally {
        this.isLoading = false;
    }
}

build() {
    Column() {
        if (this.isLoading) {
            LoadingProgress()
                .width(50)
                .height(50)
        } else if (this.userProfile) {
            // 用户信息头部
            Row() {
                Image(this.userProfile.avatar)
                    .width(80)
                    .height(80)
                    .borderRadius(40)
                
                Column() {
                    Text(this.userProfile.nickname)
                        .fontSize(20)
                        .fontWeight(FontWeight.Bold)
                    
                    Row() {
                        Text(`粉丝: ${this.userProfile.followers}`)
                            .margin({ right: 10 })
                        Text(`关注: ${this.userProfile.following}`)
                    }
                }
            }
            
            // 帖子列表
            List({ space: 10 }) {
                ForEach(this.posts, (post) => {
                    ListItem() {
                        PostItem({ post: post })
                    }
                })
            }
            .layoutWeight(1)
        }
    }
    .padding(10)
    .width('100%')
    .height('100%')
}

}
2. 帖子发布功能
// pages/CreatePostPage.ts
import { PostService } from '../services/postService';

@Entry
@Component
struct CreatePostPage {
@State content: string = ''
@State images: string[] = []

async publishPost() {
    const userId = agconnect.auth().currentUser?.uid;
    if (!userId) return;
    
    try {
        await PostService.createPost({
            userId,
            content: this.content,
            images: this.images,
            likes: 0,
            comments: 0,
            createTime: new Date(),
            updateTime: new Date()
        });
        
        // 发布成功,返回上一页
        router.back();
    } catch (error) {
        console.error('Failed to publish post:', error);
    }
}

build() {
    Column() {
        TextArea({ text: this.content })
            .onChange((value: string) => {
                this.content = value;
            })
            .height('40%')
            .width('100%')
        
        ImageUploader({
            onUploadComplete: (uris: string[]) => {
                this.images = uris;
            }
        })
        
        Button('发布')
            .onClick(() => this.publishPost())
            .width('80%')
            .margin(20)
    }
    .padding(10)
}

}
六、性能优化与安全

  1. 数据缓存策略
    // services/cacheService.ts
    import { AGCCloudDB } from '@hw-agconnect/cloud-database-harmony';

export class CacheService {
// 使用云数据库的本地缓存功能
static async getPostsWithCache(userId: string): Promise<Post[]> {
const query = AGCCloudDB.where('Post')
.equalTo('userId', userId)
.orderByDesc('createTime')
.limit(20)
.fromLocal();

    try {
        const snapshot = await cloudDB.executeQuery(query);
        return snapshot.getObjects().map(obj => obj.toObject() as Post);
    } catch (error) {
        console.log('Local cache failed, trying remote...');
        return PostService.getUserPosts(userId);
    }
}

}
2. 安全规则配置
在AGC控制台中配置安全规则:

​​认证规则​​:
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"posts": {
"$postId": {
".write": "resource.data.userId == auth.uid || root.child('admins').child(auth.uid).exists()"
}
},
"userProfiles": {
"$userId": {
".write": "$userId == auth.uid"
}
}
}
}
​​存储规则​​:
{
"rules": {
"avatars": {
"$userId": {
".write": "$userId == auth.uid"
}
},
"posts": {
"$userId": {
"$postId": {
".write": "$userId == auth.uid"
}
}
}
}
}
七、部署与发布

  1. 构建应用
    在DevEco Studio中:

选择Build > Generate HarmonyOS App Package
选择发布模式
生成.app文件
2. 上传到AppGallery Connect
登录AppGallery Connect
选择您的项目
导航到"我的应用" > "应用发布"
上传.app文件并填写应用信息
提交审核
结语
通过本教程,您已经完成了一个完整的HarmonyOS 5社交应用的开发,并集成了AGC的全栈服务。这些技术可以扩展到更复杂的社交功能开发中,如:

实时聊天(可考虑集成AGC的实时数据库)
推送通知(使用AGC的推送服务)
社交分析(使用AGC的分析服务)

posted @ 2025-06-29 22:44  暗雨YA  阅读(53)  评论(0)    收藏  举报