iet iv = self.view.viewwithTag (4)!
UIView.animate (withDuration : 2, animations: {
iv.transform = iv.transform.rotated(by: CGFloat (360))
}
let iv = self.view. viewwithTag (4)!
UIView.animate (withDuration: 2, animations: {
iv.frame.origin.x += 100
if iv.frame.origin.x > self.view.frame.size.width {
iv.frame.origin.x =
}
})
let iv = self.view.viewNithTag (4)!
UIView.animate (withDurat ion: 2, animations:{
iv.transform = CGAffineTransform (scalex: 0.8,y:0.8)
})
let iv = self.view. viewwithTag (4) !
UIView.animate (withDuration: 2, animations: {
iv.alpha = 0.1
})
import UIKit
import AVKit
class ViewController: UIViewController {
@IBAction func Play (_ sender : Any)
{
let path = Bundle.main. path (forResource: "test", ofType: "mov")
let url = URL (fileURLWithPath: path!)
let player = AVPlayer (url: url)
let playerViewController = AVPlayerViewController ()
playerViewcontroller.player = plaver
playerViewController.view.frame = CGRect (x: 20, y: 100, width:self.view.bounds.width - 40, height: 200)
self.addChild(playerViewController)
self.view.addSubview(playerViewController.view)
}
}
import UIKit
import AVKit
class ViewController: UIViewController {
@IBAction func NetworkPlay(_ sender: UIButton) {
let neturl = "http://bos.nj.bpc.baidu.com/tieba-smallvideo/117723c435014fb2dd9a5fd56a57cc369£6a0.mp4"
guard let networkurl = URL(string: neturl ) else { return }
let player = AVPlayer (url: networkUrl)
let playerViewController = AVPlayerViewController ()
playerViewController.player = player
self.present (playerViewController,animated: true,completion:nil)
}
}
import UIKit
import AVKit
import AVFoundation
classViewController: UIViewcontroller {
var playflag = false
var playerViewController = AVPlayerViewController ()
var soundPlayer : AVAudioPlayer!
override func viewDidLoad () {
super.viewDidLoad ()
let iv = self.view.viewwithTag (4)!as!UIImageView
let img = UI Image. animatedImageNamed (" Erame-", duration: 0.5)
iv.image = img
Timer.scheduledTimer (timeInterval: 2.0, target: self, selector:#selector(doTimer), userInfo: nil, repeats: true)
}
@objc func doTimer () {
let iv = self. view.viewwithTag (4) !
UIView.animate (withDuration: 2, animations: {
iv.transform = iv.transform. rotated (by: CGFloat (360))
}
})
@IBAction func onPlayAudio sender : UIButton) {
let title = sender.currentTitle
let path = Bundle.main.path(forResource: title, ofType: "mp3")
let url = URL (fileURLWithPath: path!)
soundPlaver = try? AVAudioPlayer (contentsof: url)
soundPlayer.play()
}
@IBAction func onPlayVideo (_ sender: UIButton) {
if !playFlag {
let path = Bunale.main.path (forResource: "rollinwd Id", ofType: "m4a"
let url = URL (fileURLWithPath: path!)
let player = AvPlayer (url: url)
player.play ()
playerViewcontroller.player = player
let buttonPosition = sender.frame
let x = buttonPosition .origin.x-200
let y = buttonPosition.origin.y-120
playerViewController.view. frame = CGRect (x: x, y: y , width:200, height: 112)
self.addChild (playerViewController)
self.view.addSubview (playerViewController.view)
playFlag = true
}
else {
playerViewController.view.removeFromSuperview()
playFlag = false
}
}
}
UIDeviceOrientationDidChangeNotification
NotificationCenter.default.addobserver(self,selector: #selector(receivedRotation(notification:)),name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
func receivedRotation(notification :NSNotification){
backgroundView.frame = CGRect(x: 0,y: 0,width: self.view.frame.size.width,height: self.view.frame.size.height)
}
var myString = "Hello world! - swift.jsrun.net"
print(myString)
import UIKit
class CoreGraphUIView: UIView f
override func touchesBegan ( touches: Set <UITouch>,with event: UIEvent?) (self.backgroundColor = UiColor.red
print ("Began: \(touches) ")
}
override func touchesEnded (_touches: Set <UlTouch>, with event: UIEvent?) (self, backgroundColor = UIColor.lightGray
print ("Ended: \(touches)")
}
override func touchesMoved( touches: Set<UlTouch>, with event: UIEvent?)( self, backgroundColor = Uicolor.blue
print ("Moved: \ (touches) ")
}
}
class ViewController: UIViewController(
override func viewDidLoad (0 f
super.viewDidLoad (0
//Do any additional setup after loading the view.
let height = self.view.frame.size.height
let width = self.view.frame,size,width
let graphFrame = CGRect (x: 0, y: 0, width: width,height: height)
let graphView = CoreGraphUIView (frame: graphFrame)
graphView.backgroundColor = UIColor.white
self.view.addSubview (graphView)
}
}
//如果想获得触摸的对象及其坐标,程序如下:let touch:UlTouch = touches.first! as UITouch print(touch.location(in: view).x)
print(touch.location(in: view).y)
//5.2拥有自己的绘图类
//5.2.1定义一个Shape类 1
class Shape 【
//名称
var name : String?
//边数
var sides : Int?
//左上用的位首坐标
Val origin: CGPoint?
//线条颜色
var lineColor : UIColor = UICOLOr.red
//填充颜色
var filColor: UICOLOr = UrCoLor.green//线条宽度
var linewiath : CGELoat = 2
//构造器涵数init
init (name: String, sides : Int, origin: CGPoint) (self, name = name
self.sides = sides
self.origin = origin
//自定义方法savHello
func sayhello () {
print ( "Shape is \(name!), sides \(sides!), and originCord is (\(origin!.x), \(origin!.y))")
}
}
[COImport UInit
IColclass Shape {
var name : String?
var sides: Int?
var origin : CGPoint?
var linecolor : UIColor = UICOlor.red
var fillColor : UIColor = UIColor.green
var lineWidth: CGFloat = 2
init (name : String, sides : Int, origin : CGPoint) (self.name = name
self.sides = sides
self,oriain = oriain
}
func sayhello) {
print("Shape is \(name!), sides \(sides!), and originCord is (\(originCord!.x),\(origin!.y))")
}
}
ass ViewController: UIViewController {
override func viewDidLoad 0 {
super.viewDidLoad 0
let myShape = Shape(name:"BaseShape", sides: 0, origin: CGPoint(x:0, y: 0)myshape. sayHello 0
1
import UIKit
class Shape I
//名称
var name : String?
//边数
var sides:Int?
//左上角的位置坐标
var origin: CGPoint?
//线条颜色
var lineColor: UIColor = UIColor.red
//线条宽度T
var lineWidth: CGFloat = 2
//构造器函数 init
init(name: String, sides : Int, origin: CGPoint)
self.name = name
self.sides = sides
self.origin = origin
//自定义方法 sayHe11o
func sayHello 0 (
print ("Shape: \(name!), sides \(sides!), origin ((origin!.x),\(origin!.y)) ")}
}
}
class CzfView : UIView f
//成员变量(属性)shape,共类型为Shape
var shape : Shape?
//重载UIView的draw方法
override func draw(_ rect: CGRect) ( I
//判断shape变量是否为空值nil
guard let s = shape else (
return
}
//不为空,则调用shape这个实例的方法
s.sayHello ()
}
}
class ViewController: UIViewController d
override func viewDidLoad0 (
super.viewDidLoad 0
//Do any additional setup after loading the view, typically from a nib.
//此处调用Shape类,建立一个对象(实例)myShape
let myShape = Shape(name:"BaseShape", sides: 0, origin: CGPOInt(x: 0. y: 0))
//此处建立了一个 Czfview 的买例myView
let width = self,view.frame.size,width
let height = self.view.frame.Size,height
let myView = CzfView (frame: CGreet (x: 0, y: 0, width: width,height: height))
//赋值给myView 中的成员(属性)shape
myview.shape = myShape
//显示mvView
self.view.addSubview(myview)
}
}
//在Shape类中增加一个方法drawBezierPath0,其代码如下:
//自定义方法drawBezierPath用于四冬
func drawBezlerrathO (
//调用贝基尔曲线函数UIBezierPathO
let path = UIBezierPath0 I
//圆孤的中心点center,其坐标为(100,100)
let center :CGPoint = CGPolnt (x: 100, y: 100)
//圆的半径长度radius,其值为80
let radius: CGFloat = 80
//生成一个园
Path.addare(withCenter:center, radius: radius, startAngle:0,endAngle: CGFLoat.p1*2, clockwise: true)
//线条宽度为5
path.lineWidth=5
//线条颜色为red红色
UIColor.red.setStroke0
//画出这个园
path.stroke0
}
//在CztView这个类中,修改draw方法,增加一行:
S.drawBezierrath0
//最后在ViewController的ViewDidLoad0中,清除背景色,不然会出现黑色背景,具体增加的代码如下:myview.backgroundColor=UIColor.clear
//清余背景色
//5.3绘制平面几何图形
//5.3.1常见图形绘制
//基类Shape
class Shape (
//名称
var name: String?
//左上角的位置坐标
var origin : CGPoint?
//线条颜色
var lineColor: UIColor? = UIColor.red
//填充颜色
var fil1color: UIColor? = UIColor .green
//线条宽度
var lineWidth : CGFloat? = 5
//构造器函数init
init(name : String, origin: CGPoint) (
self.name = name
self.origin = origin
)
//便利构造器函数init
convenience init(origin : CGPoint) f
self.init(name:"Shape Bassclass", origin: origin)
//自定义方法drawBezierPath用于画图
func drawBezierPathOf
//向控制台输出信息
print("Draw \(name!)")
}
}
//线段类Line
class Line : Shape (
//线段的起点
var start : CGPoint?
//线段的终点
var end: CGPoint?
//构造器
init (name: String, origin: CGPoint, start : CGPoint, end: CGPoint) (super.init (name: name, origin: origin)
self.start = start
self.end = end
}
convenience init (start : cGPoint, end: cGPoint) {
self -init (name: "line", origin: start, start: start, end: end)
override func drawBezierPath 0 {
print ("Draw \(name!)")
let path = UIBezierPath)
path.move (to: start!)
path.addLine (to: end!)
path.linewidth = linewidth!
path.lineCapStyle = .rouna
linecolor?.setstroke()
path.stroke()
}
}
class Rectangle : Shape (
//左上角采用基类Shape中的属性origin
//宽度和高度, 般可以采用CGS1ze
var size : CGSize?
//构造器
inst(name: String, origin: CGPoint , size : CGSize) {
super.init (name: name, origin: origin)
self.size = size
convenience init (origin: CGPoint , size: CGSize){
self.init(name:"Rectangle", origin: origin, size; size)
1
override func drawBezierPath 0{
let path = UrBezierPath(rect: CGRect (origin: origin!, size: size!))
path.lineWidth = lineWidth!
lineColor?.setstroke ()
path.stroke ()
}
}
class Rectangle : Shape (
//左上角采用基类 Shape 中的属性origin
//宽度和高度,一般可以采用CGSize
var size: CGsize?
//圆角的大小
var corner: CGFloat?
//构造器
init (name: String, origin: CGPoint, size: CGSize, corner : CGFloat) f
super.init (name: name, origin: origin)
self.size = size
self.corner = corner
convenience init (origin: CGPoint, size: CGSize, corner: CGFloat =0) f
self.init(name: "Rectangle", origin: origin, size: size, corner: corner)
)
//重载drawBezierPath方法
override func drawBezierPathO(
//向控制台输出信息
print ("Draw \(name!) ")
//建立一个UIBezierPath实例对象
let path = UIBezierPath(roundedRect : CGRect (origin : origin! size: size!), cornerRadius : corner!)
//设置实例path的线条宽度
path.lineWidth = linewidth!
// 设置实例path的线条颜色
lineColor?.setStroke ()
//画出线条
path.stroke ()
}
}
//调用代码如下:
let myRect = Rectangle(origin: start, size: CGSize (width: 150, height: 100),corner : 8.0)//则会生成一个带圆角的矩形。如果调用方法如下:
let myRect = Rectangle(origin: start, size: CGSize (width: 150, height: 100))
//则会生成一个不带圆角的普通矩形,因为在类的便利构造器中,corner默认数是0,也就是相当于圆角为0
//圆形类Circle
class Circle: Shape (
//圆心坐标 I
var center: CGPoint?
//半径长度
var raduis : CGFloat?
//椭圆的宽度和高度, 般可以采用CGSize
var size : cGsize?
//构造器
init(name: String, origin: CGPoint, center : CGPoint, raduis : CGFloat, size: CGSize) (super.init (name: name, origin: origin)
self.center = center
self.raduis = raduis
self.size = size
]
convenience init(center: CGPoint,raduis: CGFloat)(
let x =center.x- raduis
let y= centery-raduis
self.init(name: "Oval/Ellipse", origin: CGPoint (x:x, y:y),center:center, raduis: 0, size: size)
//重载dranBezierPath方法
override func drawBezierPath Of
//向控制台输出信息
print ("Draw\(name!)")
//建立一个UIBezierPath实例对象
let path = UIBezierPath(ovalln: CGRect(loriginorigin!, size:size!))
//设置实例path的线条宽度
path.linewidth = linewidth!
//设置实例path的线条颜色
linecolor?.setStroke ()
//画出袋条
path. stroke ()
}
}
//多边形类Polygons
class Polygons : Shape (
//多边形主要是通过多个顶点相互连接来绘图
//顶点数组
var points : Array<CGPoint>?
init(name: String, origin: CGPoint, points: Array<CGPoint>) (
super,init(name: name, origin: origin)
self,points = points
)
convenience init (points : Array<CGPoint>)(
if points.count == 3 (
self.init(name: "Triangel", origin: points.first!, points:points)
else if points.count >= 3 (
self.init (name: "Polygons", origin: points.first!, points: points)
else I
let origin = CGPoint (x: 0, y; 0)
self.init (name:"Error, origin: origin, points: points")
1
1
//重載drawBezierPath方法
override func drawBezierPathO (
//向控制台输出信息
print ("Draw \(name!) ")
//如果不能识别,直接返问
if(name == "Error"){
return
}
let path = UIBezierPath
pach.move (to: origin!)
for each in points! {
path.addLine (to: each)
}
path.close ()
path.lineWidth = lineWidth!
lineColor?.setstroke ()
path.stroke ()
path.fill ()
}
}
override func drawBezierPath () {
print("Draw \(name!)")
if (name =="Error") {
return
}
path = UIBezierPath ()
path?.move (to: origin!)
for each in points! {
path?.addLine (to: each)
}
path?.close()
path?.linewidth = 1inewidth!
linecolor?.setstroke ()
path?.stroke ()
path?.fi11()
}
}
class Fivestar : Shape {
var center : CGPoint?
var radius : CGFloat?
var angel : CGFloat?
init(name: string, origin: CGPoint, center : CGPoint, radius : CGFloat,angel : CGFloat, soundFile : String = "SO.m4a") {
super.init (name: name, origin: origin, soundFile: soundFile)
self.center = center
self.radius = radius
self.angel = angel
}
convenience init(center : CGPoint, radius: CFloat, angel: CGFloat = 0) {
let x = center.x - radius
let y = center.y - radius
self.init (name: "FiveStar", origin: CGPoint (x:x, y:y) , center: center,radius: radius, angel: angel)
}
override func drawBezierPath () {
print ("Drav \(name!)")
path = UIBezierPath()
let i = 360 /angel!
let xzAngle = CGFloat.pi*2/i
let xzX = (center?.x)!- sin(xzAngle) *radius!
let xzY = (center?.y)! - cos(xzAngle) *radius!
let pl = CGPoint (x:xzX,y:xzY)
path?.move(to: p1)
let angle = CGFloat.pi*4/5
for i in 1...5 {
let x = (center?.x)! - sin(CGFloat (i)*angle+xzAngle)*radius!
let y = (center?.y)!= cos(CGFloat (i)*angle+xzAngle)*radius!
path?.addLine (to: CGPoint (x: x, y: y) )
}
path?.close ()
if selectedFlag {
let dashes: [CGFloat] = [1, 3]
path?.setLineDash (dashes, count: dashes. count, phase: 0)
}
path?.lineWidth = lineWidth!
linecolor?.setstroke()
path?. stroke ()
}
}
marile: soundstle
class czfview : UIview {
private var shapes : Array<Shape> = []
override fune draw( rect : cGRect) {
for s in shapes {
s. drawBezierPath()
}
}
func add (shape : Shape) {
shapes.append (shape)
}
override func touchesBegan (_ touches: Set<UITouch>, with event: UIEvent?) {
let touch : UITouch = touches.first! as UIrouch
let point = touch . location (in: self)
for s in shapes {
if s.isSelected (point: point) {
s.playAudio ()
self.setNeedsDisplay()
}
}
}
}
class ViewController: UIViewController {
override func viewDidLoad () {
super.viewDidLoad ( )
let starcenter = CGPoint (x: 180,y: 180)
let star = FiveStar(center: starCenter, radius: 50, angel: 45)
star.linecolor = UIColor.blue
let ovalCenter = CGPoint (x: 100, y: 300)
let ovalsize = CGsize (width : 100, height: 60)
let oval = Circle (center: ovalCenter, size: ovalSize)
let rectorigin = CGPoint(x: 60,y:50)
let rectsize = CGSize(width: 100, height: 50)
let rect = Rectangle(origin: rectOrigin, size: rectSize, corner: 6)
rect.lineColor = UIColor.gray
let myView = Czfview (frame: CGRect (x: 0, y: 0, width: self.view.frame.size.width, height: self.view .frame .size.height))
myView.backgroundColor = UIColor.clear
myView.add (shape: star)
myView.add (shape: oval)
myView.add (shape: rect)
self.view.addSubview (myView)
}
}
{
"refresh_token": "25.b55fe1d287227ca97aab219bb249b8ab.315360000.1798284651 .282335-8574074"
"expires in": 2592000,
"scope":"public wise adapt",
"session_ key": "9mzaDZXu3dENdEZQurfgOVz8s1gSgvvOAUebNFzyzcp05EnbxbF+ h£G9DQkpUVQdh4p6HbQcAiz5RmuBAjalJJGgIdJI",
"access_ token": "24.6c5e1 £f107f0e8bcef8c45a3424a0e78 .2592000.1485516651.
282335-8574074",
"session secret": "Afac94a3489fe9fca7c3221cbf7525ff"
}
{
"error": "invalid client",
"error_description": "unknown client id"
}
# encoding: utf-8
import requests
#Client id 为官网获取的 AK, client secret 为官网获取的 SK
host = 'lhttps:
credentials&client_id= 【官网获取的 AK】 &client secret= 【官网获取的 SK】'
response = requests.get(host)
if response
print(response.json())
import requests
import base64
'''
车型识别
''''
request_url = "https://aip.baidubce.com/rest/2.0/image-classiEy/v1/
car"
# 二进制方式打开图片文件
£ = open([本地文件],'rBr')
img = base64.b64encode (f. read ())
params = "{"image" :img, "top_num":5}
access_token = "[调用签权接口获取的 token],
request_url = request url + "?access token=" + access_token
headers = {'content-type!': 'application/ x-www-form-ur1encoded'}
response = requests.post (request_url, data-params, headers-headers)
if response:
print (response.json ())
返回的 JSON 数据:
{
"log_id”: 4086212218842203806,
"location result": {
"width": 447,
"top": 226,
"height": 209,
"left": 188
},
"result":[
"baike info": {
"baike url: "http://baike.baidu.com/iten/E5%B8%83%5%82%A08E8BFAAchi
ron/20419512",
rdescription":〞布加迪 Chiron 是法国跑车品牌布加迪出品的豪华超跑车。配置四涡轮
增压发动机,420 公里每小时,有23种颜色的选择。售价高达 260万美元。“
},
"score": 0.98793351650238,
"name”:" 布加迫 Chiron",
"year":"无年份信息"
},
{
"score": 0.0021970034576952,
"name”:” 奥迫RS5",
"year": "2011-2017"
},
{
"score": 0.0021096928976476
*2
{
"Name": "Chen Zhifeng",
"Profession": "Teacher",
"Age": 46,
"Email": "13402506301@163.con",
"Eriends" : InZhang San", "Li si"]
}
{
"TeamName":"i0S-Orange-Team",
"Teacher": "Chen Zhifeng",
"Students": [
{ "Name": "Zhang Bo","Hometown": "Xuzhou"'},
{"Name": " Chang Wenxiang ", "Hometown": "Yancheng"),
{"Name" :" Hu Yinting". "Hometown": "Suzhou"}
]
}
{
"coord": ("lon": -0.13, "lat": 51.51},
"weather": ("id": 300, "main": "Drizzle", "description": "light
intensity drizzle", "icon": "09d"} ],
"base":"stations"
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp min":279.15,
"temp_max":281.15
},
"visibility": 10000,
"wind": ("speed": 4.1, "deg": 801},
"clouds": ("all": 90},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise" :1485762037
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod":200
}
*3
{
"Name": "Chen Zhifeng",
"Profession": "Teacher",
"Age": 46,
"Email": "13402506301@163.con",
"Eriends" : InZhang San", "Li si"]
}
{
"TeamName":"i0S-Orange-Team",
"Teacher": "Chen Zhifeng",
"Students": [
{ "Name": "Zhang Bo","Hometown": "Xuzhou"'},
{"Name": " Chang Wenxiang ", "Hometown": "Yancheng"),
{"Name" :" Hu Yinting". "Hometown": "Suzhou"}
]
}
{
"coord": ("lon": -0.13, "lat": 51.51},
"weather": ("id": 300, "main": "Drizzle", "description": "light
intensity drizzle", "icon": "09d"} ],
"base":"stations"
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp min":279.15,
"temp_max":281.15
},
"visibility": 10000,
"wind": ("speed": 4.1, "deg": 801},
"clouds": ("all": 90},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise" :1485762037
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod":200
}
*4
Func sessionGetData () {
let urlstring = "http: //www.tuling123.com/"
let url = uRL (string: urlstring)
let request = URLRequest (url: url!)
let session = URISession . shared
iet datarask = session.dataTask (with: request,
completionHandler: ( (data, response, error) -> Void in
if error != nilf{
print (error.debugDescription)
}else{
let str = String (data: data!, encoding:
String. Encoding.utf8)
print (str!)
}) as URLSessionTask
dataTask. resume ( )
}
func sessionDownloadImage () {
let url = URL (string: "http: / /hangge.com/blog/ images/logo.png")
let request = ULRequest (url: url!)
let session = URLSession.shared
let downloadTask = session. downloadTask (with: request,
completionHandler: {
(location : URL?, response : URLResponse?, error:ErrOr?)
-> Void in
print ("location : 1 (string (describing : 1ocation))")
let locationPath = location?.path
let now = NsDate ()
let timeInterval: TimeInterval = now. timeIntervalSince1970
let timestamp = String (timeInterval)
let documents: String = NSHomeDirectory () + "/Documents/\(timeStamp).png"
let fileManager = FileManager. default
try! fileManager moveItem (atPath: locationPath!, toPath:documents)
print ("new location: 1 (documents)")
} )
downloadTask.resume ()
}
<?php
php 接收流文件
* @param String $file 接收后保存的文件名
* @return boolean
* /
function receiveStreamFile ($receiverile) {
$streampata = isset (SCLOBALST 'HTTP RAW POST_ DATA'])? SGLOBATS L'HTTP_RAW POST DATA'] : '';
if (empty ($streamData)) {
$streamData = file_get_contents ('php:
}
if ($streamData!='') {
$ret = file _put_contents ($receiveFile, $streamData, true);
}else {
$ret = false;
}
rqeeturn $ret;
}
$receiverile = $_SERVERL" DOCUMENI ROOT"J ."/ uploadFiles / swift . png";
echo $receiveFile;
$ret = receiveStreamFile ($receiveFile) ;
echo json_ encode (array ('success ' => (bool) sret))i
?>
func sessionUploadPhp () {
let uri = URL(string: "http://localhost/uploadSwift.php")
let session = URLSession.shared
var request - URLecuest (url: uri!, cachePolicy: •reloadIgnoringCacheData)
request.httpMethod = "POST"
iet tileImage = Bundle. main.path (forResource : "beel ", ofType: "png")
iet ingData = try! Data (contentsOf: URL (til eURIWi thPath: tileImage !))
let uploadIask = session.uploadTask (with: request as URLRequest, from:imaData) {
(data: Data?, response: URLResponse?, error:Error?) -> Void in
if error != nill
print (error!)
}else {
let str = string (data: data!, encoding: string .Encoding .utf8)
print("上传完毕:\(String (describing:stz))")
}
}
uploadTask.resume ()
}
*5
import UIKit
import Foundation
let API Key = "EIpAlhdD715152EsiNgpUOF_"
let Secret Key = "P8EzWg4agjDOxABmKVBYSNyZ1YzGFqb_"
let token_ host = "https: //aip.baidubce.com/oauth/2.0/token?grant_type=client_ credentials&client id=\(API Key) &client secret =\ (Secret_Key)"
var access token = ""
var expires in: Int32 = 0
if let url = URL (string: token host) {
URLSession. shared. dataTask (with: url) (data, response, error) in
if error != nil {
print ("network error")
}
else {
if let json = try? JSONSerialization.jsonObject (with: data!,options: allowFragments) as?[String:Any] {
access token = json ["access token"] as! String
expires in = ison["expires_in"las! Int32
print ("--------accesstoken------")
printaccess token)
print ("--------expires_time------")
print (expires_in)
}
}
}.resume()
}
else {
print("url error")
}
public struct Loader
static func readTxt (file url:URI) ->String? {
do {
let source = try String (contentsOf: ur1)
return source
}
catch {
return nil
}
}
static func readBin (file url:URL) 一> Data? {
do {
let data = try Data (contentsOf: url)
return data
}
catch {
return nil
}
}
}
let path = Bundle. main.path (forResource: "grcar. jpg", ofType: nil)
let url = URL (fileURLWithPath: path!)
let data = Loader.readBin (file: url)
if(data == nil) {
print ("File failed to load")
}
let data base64 str = data? .base64EncodedString()
let data base64 = data?.base64EncodedData ( )
access token="24.2ec96a68£742842900£07869929413ae.2592000.1598921312.282335-21737249"
let carType host ="https://aip.baidubce.com/rest/2.0/image-classify/v1/car" + "?access_token=" + "\(access_token)"
if let url = URL(string: carType_host)
var request = URLRequest (url: ur1)
request. setValue ("application/×-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
let cs = NSCharacterSet (charactersIn: "/=+%") inverted
let image_urlEncode = data base64 str!addingPercentEncoding (withAllowedCharacters: cs)
let postString = "image=\(image urlEncode!) &top num=5&baike_num-1"
request.httpBody = postString.data (using:utf8)
URLSession.shared.dataTask(with: request) { (data,response, error) in
if error != nil {
print ("error")
}
else {
let rs = String (data: data!, encoding: String. Encoding.utf8)
print(rs!)
}
}
.resume ()
}
{
“log id" : 4368540366187197442,
"location result:
{
"width":386.4585876464844,
"top": 81.3405532836914,
"height": 183.9795532226562,
"left": 58.03330230712891
},
"result":
[
{
"score":0.9767324924468994,
"year": "2014-2017",
"baike_info":
{
"baike url": i/item/8E5gA5%87%87%91%9EE5/475143",
"image arl":
"/pic/5882b2b7a0a20cf47a91d7777c094b36acaf9910",
"description":
"2014 款奇瑞巴5 是国内科技家桥的引领者,带领消费者悦享领先科技。"
},
"name":"奇瑞E5"
},
{
"score : 0.007103727199137211,
"name":"奇瑞旗云",
"year": "2010-2013"
},
{
"score":0.003686367534101009,
"name":"奇瑞艾瑞泽 7",
"year": "2016-2017"
},
{
"score": 0.001757977530360222,
"name":“ 奇瑞53”,
"year": "2015-2017"
},
{
"score": 0.001047104829922318,
"name ":“ 奇瑞A5",
"year": "2015"
}
],
"color result" " 黒色"
}