iOS 关于自动打包那些事

作为一名程序猿,能用代码解决的事情,恩,就用代码解决!

首先并没有想到造轮子,就去找轮子,但是并没有找到合适的轮子,因为轮子大多数是 xcrun 的打包方式 现在被废弃了已经,于是按照 Apple 的官方文档换成 xcodebuild 慢慢‘造’轮子了 ,附 xcodebuild 官方文档

deprecated.png

本文提供 :
(1) 自动打包
(2) 打包完成后发布到蒲公英
(3) 发布完成后发送邮件给测试人员

一、自动打包

使用 Apple 提供的 xcodebuild 命令,执行打包并导出为ipa包。

  • Archive
    project 的打包方式
buildCmd = 'xcodebuild archive -project %s -scheme %s -configuration %s -sdk %s -archivePath %s/%s.xcarchive' %(project,scheme,CONFIGURATION,SDK,buildDir,scheme)

workspace 的打包方式(供集成Cocoapods项目使用)

buildCmd = 'xcodebuild archive -workspace %s -scheme %s -configuration %s -sdk %s -archivePath %s/%s.xcarchive' %(workspace,scheme,CONFIGURATION,SDK,buildDir,scheme)
  • Export ipa
ipaCmd = 'xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s -exportFormat ipa -exportProvisioningProfile %s' %(buildDir,scheme,output,PROVISIONING_PROFILE)

二、打包完成发送到蒲公英

一般 公司都有企业账户的,打完包让测试人员测,或者公司内部人员提前使用,我们用的蒲公英,就以此为例,此处可以替换为别的工具,基本上所有的工具都会有Api文档告诉你如何用脚本上传到服务器。


iOS 关于自动打包那些事_第1张图片
屏幕快照 2016-11-22 下午5.06.03.png
print "ipaPath:"+ipaPath
    files = {'file': open(ipaPath, 'rb')}
    headers = {'enctype':'multipart/form-data'}
    payload = {'uKey':USER_KEY,'_api_key':API_KEY,'publishRange':'2','isPublishToPublic':'2'}
    print "uploading...."
    r = requests.post(PGYER_UPLOAD_URL, data = payload ,files=files,headers=headers)
    if r.status_code == requests.codes.ok:
         result = r.json()
         parserUploadResult(result)
    else:
        print 'HTTPError,Code:'+r.status_code

三 、发送邮件给测试人员

发布到测试平台后,你需要告诉别人,此时发邮件功能就可以用上了,没有什么特别的,Google一下 python 发邮件 就可以得到很多脚本了。但你一定要注意第三方邮件的坑,记住发件方要开启SMPT。
笔者用的163邮箱

msg = MIMEText('xx iOS测试项目已经打包完毕,请前往 http://www.pgyer.com/xx 下载测试!', 'plain', 'utf-8')
    msg['From'] = _format_addr('自动打包系统 <%s>' % from_163_addr)
    msg['To'] = _format_addr('xx 测试人员 <%s>' % to_addr)
    msg['Subject'] = Header('xx iOS客户端打包程序', 'utf-8').encode()
    server = smtplib.SMTP_SSL(smtp_163_server, 465)
    server.connect(smtp_163_server, 465)
    server.set_debuglevel(1)
    server.starttls()
    server.ehlo()
    server.login(from_163_addr, password)
    print "开始发送邮件。。。"
    server.sendmail(from_163_addr, [to_addr], msg.as_string())
    server.quit()
    print "发送邮件完成"

附录 :名词解释

  • project

工程根目录。project.xcodeproj

  • workspace

工程根目录。workspace.xcworkspace


iOS 关于自动打包那些事_第2张图片
workspace.png
  • scheme

项目名称


iOS 关于自动打包那些事_第3张图片
scheme.png
  • configuration

打包的话直接 Release

  • sdk

iOS 固定 iphoneos

  • exportProvisioningProfile

开发的配置文件 ProvisioningProfile

iOS 关于自动打包那些事_第4张图片
ProvisioningProfile.png

注意
iOS 关于自动打包那些事_第5张图片
Profile.png

脚本用法 :

from optparse import OptionParser
import subprocess
import requests
import hashlib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
#configuration for iOS build setting

PROVISIONING_PROFILE = "profilexxx" //换成你的
CONFIGURATION = "Release"
SDK = "iphoneos"

# configuration for pgyer
PGYER_UPLOAD_URL = "http://www.pgyer.com/apiv1/app/upload"
DOWNLOAD_BASE_URL = "http://www.pgyer.com"
USER_KEY = "xxx"    //换成你蒲公英账号的
API_KEY = "xxx"     //换成你蒲公英账号的

# configuration for email   //换成你需要的邮箱地址
from_gmail_addr = "[email protected]"
from_163_addr = "[email protected]"
password = "xxx"
smtp_gmail_server = "smtp.gmail.com"
smtp_163_server = "smtp.163.com"
to_addr = '[email protected]'
pgyer_addr = "http://www.pgyer.com/xx"


def cleanBuildDir(buildDir):
    cleanCmd = "rm -r %s" %(buildDir)
    process = subprocess.Popen(cleanCmd, shell = True)
    process.wait()
    print "cleaned buildDir: %s" %(buildDir)


def parserUploadResult(jsonResult):
    resultCode = jsonResult['code']
    if resultCode == 0:
        downUrl = DOWNLOAD_BASE_URL +"/"+jsonResult['data']['appShortcutUrl']
        print "Upload Success"
        print "DownUrl is:" + downUrl
    else:
        print "Upload Fail!"
        print "Reason:"+jsonResult['message']

def uploadIpaToPgyer(ipaPath):
    print "ipaPath:"+ipaPath
    files = {'file': open(ipaPath, 'rb')}
    headers = {'enctype':'multipart/form-data'}
    payload = {'uKey':USER_KEY,'_api_key':API_KEY,'publishRange':'2','isPublishToPublic':'2'}
    print "uploading...."
    r = requests.post(PGYER_UPLOAD_URL, data = payload ,files=files,headers=headers)
    if r.status_code == requests.codes.ok:
         result = r.json()
         parserUploadResult(result)
    else:
        print 'HTTPError,Code:'+r.status_code

def buildProject(project, scheme, output):
  
    process = subprocess.Popen("pwd", stdout=subprocess.PIPE)
    (stdoutdata, stderrdata) = process.communicate()
    buildDir = stdoutdata.strip() + '/build'
    print "buildDir: " + buildDir
    buildCmd = 'xcodebuild archive -project %s -scheme %s -configuration %s -sdk %s -archivePath %s/%s.xcarchive' %(project,scheme,CONFIGURATION,SDK,buildDir,scheme)
    print "buildCmd: " + buildCmd
    process = subprocess.Popen(buildCmd, shell = True)
    process.wait()
    
    ipaCmd = 'xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s -exportFormat ipa -exportProvisioningProfile %s' %(buildDir,scheme,output,PROVISIONING_PROFILE)
    process = subprocess.Popen(ipaCmd, shell=True)
    (stdoutdata, stderrdata) = process.communicate()

    uploadIpaToPgyer(output)
    cleanBuildDir(buildDir)

def buildWorkspace(workspace, scheme, output):
    process = subprocess.Popen("pwd", stdout=subprocess.PIPE)
    (stdoutdata, stderrdata) = process.communicate()
    buildDir = stdoutdata.strip() + '/build'
    print "buildDir: " + buildDir
    buildCmd = 'xcodebuild archive -workspace %s -scheme %s -configuration %s -sdk %s -archivePath %s/%s.xcarchive' %(workspace,scheme,CONFIGURATION,SDK,buildDir,scheme)
    process = subprocess.Popen(buildCmd, shell = True)
    process.wait()
        
    ipaCmd = 'xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s -exportFormat ipa -exportProvisioningProfile %s' %(buildDir,scheme,output,PROVISIONING_PROFILE)
    process = subprocess.Popen(ipaCmd, shell=True)
    (stdoutdata, stderrdata) = process.communicate()
        
    uploadIpaToPgyer(output)
    cleanBuildDir(buildDir)

def xcbuild(options):
    project = options.project
    workspace = options.workspace
    scheme = options.scheme
    output = options.output

    if project is None and workspace is None:
        pass
    elif project is not None:
        buildProject(project, scheme, output)
    elif workspace is not None:
        buildWorkspace(workspace, scheme, output)


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

# 发邮件
def send_mail():

    msg = MIMEText('xx iOS测试项目已经打包完毕,请前往 xxx 下载测试!', 'plain', 'utf-8')
    msg['From'] = _format_addr('自动打包系统 <%s>' % from_163_addr)
    msg['To'] = _format_addr('xx 测试 <%s>' % to_addr)
    msg['Subject'] = Header('xx iOS客户端打包程序', 'utf-8').encode()
    server = smtplib.SMTP_SSL(smtp_163_server, 465)
    server.connect(smtp_163_server, 465)
    server.set_debuglevel(1)
    server.starttls()
    server.ehlo()
    server.login(from_163_addr, password)
    print "开始发送邮件。。。"
    server.sendmail(from_163_addr, [to_addr], msg.as_string())
    server.quit()
    print "发送邮件完成"
    
def main():
    parser = OptionParser()
    parser.add_option("-w", "--workspace", help="Build the workspace name.xcworkspace.", metavar="name.xcworkspace")
    parser.add_option("-p", "--project", help="Build the project name.xcodeproj.", metavar="name.xcodeproj")
    parser.add_option("-s", "--scheme", help="Build the scheme specified by schemename. Required if building a workspace.", metavar="schemename")
    parser.add_option("-t", "--target", help="Build the target specified by targetname. Required if building a project.", metavar="targetname")
    parser.add_option("-o", "--output", help="specify output filename", metavar="output_filename")
    (options, args) = parser.parse_args()

    print "options: %s, args: %s" % (options, args)
# 编译文件打包上传到蒲公英,或者别的平台
    xcbuild(options)
# 发送邮件给测试人员,如果不需要就移除此功能
    send_mail()



if __name__ == '__main__':
    main()

在 GitHub 上将脚本下载下来,放入工程根目录,修改里面的‘xx’内容,注意:Python语言中的空格和tab缩进会受制表符影响,要保持一致性。
配置好打包需要的环境后 ,打开命令行工具 cd 工程文件夹 进入根目录
然后输入

//project 方式
./auto_ipa.py -p youproject.xcodeproj -s youproject -o ~/Desktop/youproject.ipa
//workspace 方式
./auto_ipa.py -w youproject.xcworkspace -s youproject -o ~/Desktop/youproject.ipa

20161126号更新:支持导出 AdHoc 和 AppStore ipa

xcodebuild -help 查看xcodebuild的可使用命令,在导包时加入-exportOptionsPlist 即可。此处需要一个plist文件。

iOS 关于自动打包那些事_第6张图片
2016-11-26 1.png

在图中可以看到 exportOptionsPlist里面的 method 可以配置 app-store, ad-hoc, package, enterprise, development, and developer-id,默认为 development.

  • Archive
    project 的打包方式
buildCmd = 'xcodebuild archive -project %s -scheme %s -configuration %s -sdk %s CODE_SIGN_IDENTITY="%s" PROVISIONING_PROFILE="%s" -archivePath %s/%s.xcarchive' %(project,scheme,CONFIGURATION,SDK,ADHOC_CODE_SIGN_IDENTITY,ADHOC_PROVISIONING_PROFILE,buildDir,scheme)
#AdHoc打包用AdHoc对应的profile文件
#AppStore打包用AppStore对应的profile文件

workspace 的打包方式(供集成Cocoapods项目使用)

 buildCmd = 'xcodebuild archive -workspace %s -scheme %s -configuration %s -sdk %s CODE_SIGN_IDENTITY="%s" PROVISIONING_PROFILE="%s" -archivePath %s/%s.xcarchive' %(workspace,scheme,CONFIGURATION,SDK,ADHOC_CODE_SIGN_IDENTITY,ADHOC_PROVISIONING_PROFILE,buildDir,scheme)
#AdHoc打包用AdHoc对应的profile文件
#AppStore打包用AppStore对应的profile文件
  • Export ipa
ipaCmd = 'xcodebuild -exportArchive -archivePath %s/%s.xcarchive -exportPath %s -exportOptionsPlist %s' %(buildDir,scheme,output,ADHOCPath)
  • AdHocExportOptions.plist
    AdHoc打包:key: method value: ad-hoc
    AppStore打包:key: method value: app-store
    你也可以根据需要配置除 method 之外的属性
    使用方法和上面一样。

照例放Demo,仅供参考,如有问题请留言
Demo地址:
https://github.com/yongliangP/auto_ipa 用心良苦请 star
如果你觉得对你有帮助请点 喜欢 哦,也可以关注 我,每周至少一篇技术。
或者关注 我的专题 每周至少5篇更新,多谢支持哈。

你可能感兴趣的:(iOS 关于自动打包那些事)