Swift Project Setup

Source: Internet
Author: User

1. Project Code StructureThe following is the structure of my project, using the Cocoapods management. Metadata store model data, Modules store the third-party library used by the function module
#source "Https://github.com/CocoaPods/Specs"
#source "Https://github.com/shuleihen/Specs"

# Uncomment this line to define a global platform for your project
Platform:ios, ' 8.0 '

Target ' crossborder ' do
# Comment This line if you ' re not using Swift and don ' t want to use dynamic frameworks
use_frameworks!

# Pods for CrossBorder
Pod ' Reactivecocoa '
Pod ' Alamofire ', ' ~> 3.4 '
Pod ' objectmapper ', ' ~> 1.3 '
# pod ' alamofireobjectmapper ', ' ~> 3.0 '
Pod ' Cryptoswift '
Pod ' keychainaccess '
Pod ' Xcglogger ', ' ~> 3.3 '
Pod ' Pkhud '
Pod ' sqlite.swift ', ' ~> 0.10.1 '
Pod ' Dynamiccolor '
Pod ' Snapkit ', ' ~> 0.30.0.beta1 '
Pod ' Mbprogresshud ', ' ~> 0.9.2 '
Pod ' realmswift ', ' ~> 1.0.0 '
Pod ' r.swift ' End is the class library used by the Podfile file, Alamofire is the network library, Ojectmapper is the JSON to model library and so on. You can check it yourself on GitHub. 2. API Data FormatThe JSON data format returned by the general server is: {
"RetCode": "200"
"Retmsg": ""   "Retresult":{}}RetCode for protocol code, where code and HTTP return code differently, here code is the HTTP request succeeds, the server responds to the request to return the processing code. Typically 200 or 0000 indicates success, and if the server handles the error, the error description is given in retmsg. retmsg The error content returned by the server. Due to multi-platform customer service and cross-border issues, retmsg does not necessarily serve ashint copy. Therefore, the app side will save a server code and error description of the corresponding table (can be multi-lingual), if the server returned error code, according to the code query corresponding error copy, encapsulated into Nserror passed to the upper layer use. Retresult handles the successful return of data for the API interface, and sometimes the API interface processing succeeds no data return is empty. As to whether the Retresult data is going to be debated on the model web, for the time being, we consider the simplicity and legibility of the code, and still use the Turn model mode. OC already has a lot of more mature JSON to model library (for example: mjextension), Swift also has good class library, I use Objectmapper. 3. Data ModelUse Objectmapper to log back to the user object as an example: import Objectmapper
Class User:mappable {

var accesstoken:string?
var expresstime:string?
var gesturepassword:string?
var userid:string?
var phone:string?

Init () {

}

Required init? (_ Map:map) {

}

Func Mapping (MAP:MAP) {
Accesstoken <-map["Accesstoken"]
Expresstime <-map["Expresstime"]
Gesturepassword <-map["Gesturepassword"]
UserID <-map["userid"]
Phone <-map["Phone"}} 4, Response return processingRestfull API Hostlet Url_host = ""//Restfull API Pathenum urlpath:string {
Case Login = "User/login" Case loginout = "remit/loginout"}//Restfull API Response structenum responsedata:st Ring {
Case Code = ' RetCode ' case Msg = ' retmsg ' case Result = ' Retresult ' case Success = "0000"
}

Class Network {
class Func Request (Method Method:Alamofire.Method,
Path:urlpath,
Parameters:[string:anyobject]? = nil)-Alamofire.request {

Let urlstring = Url_host + path.rawvalue
Let encoding = Alamofire.ParameterEncoding.JSON
Let headers = AppContext.sharedInstance.commRESTHeader ()

Let request = Manager.sharedInstance.request (method, URLString, Parameters:parameters, encoding:encoding, headers: Headers

NSLog ("\n/*----Request----\n\ (request.debugdescription) \ n------------------*/\n\n")
Return request
}

static Let queue = Dispatch_queue_create ("Com.crossborder.network", dispatch_queue_serial)
}

Mark:object
Extension Request {

public func responseobject<t:mappable> (completionhandler:response<t, nserror>, Void)-Self {
Return RESPONSE_CB {response in
If response.result.isSuccess {
Let value = mapper<t> (). Map (Response.result.value)
Let result = Result<t, nserror>. Success (value!)

Let RSP = Response<t, nserror> (
Request:response.request,
Response:response.response,
Data:response.data,
Result:result,
Timeline:response.timeline
)

Dispatch_async (Dispatch_get_main_queue ()) {Completionhandler (RSP)}
} else {
Let result = Result<t, nserror>. Failure (response.result.error!)

Let RSP = Response<t, nserror> (
Request:response.request,
Response:response.response,
Data:response.data,
Result:result,
Timeline:response.timeline
)

Dispatch_async (Dispatch_get_main_queue ()) {Completionhandler (RSP)}
}
}
}
}

Mark:array
Extension Request {

public func responsearray<t:mappable> (Completionhandler:response<[t], nserror>, Void)-Self {
Return RESPONSE_CB {response in
If response.result.isSuccess {
Let value = mapper<t> (). Maparray (Response.result.value)
Let result = Result<[t], nserror>. Success (value!)

Let RSP = Response<[t], nserror> (
Request:response.request,
Response:response.response,
Data:response.data,
Result:result,
Timeline:response.timeline
)

Dispatch_async (Dispatch_get_main_queue ()) {Completionhandler (RSP)}
} else {
Let result = Result<[t], nserror>. Failure (response.result.error!)

Let RSP = Response<[t], nserror> (
Request:response.request,
Response:response.response,
Data:response.data,
Result:result,
Timeline:response.timeline
)

Dispatch_async (Dispatch_get_main_queue ()) {Completionhandler (RSP)}
}
}
}
}

Mark:dictionary
Extension Request {

public func responsedictionary (Completionhandler:response<anyobject, nserror>, Void)-Self {
Return RESPONSE_CB {response in
Dispatch_async (Dispatch_get_main_queue ()) {Completionhandler (response)}
}
}

Public func RESPONSE_CB (queue queue:dispatch_queue_t? = Network.queue, Completionhandler:response<anyobject, Nserror>, Void)
Return response (Queue:queue, ResponseSerializer:Request.DictionaryMapperSerializer (), Completionhandler: {response Inch
If Response.result.isFailure {
Dispatch_async (Dispatch_get_main_queue ()) {Errorhandler.handler (Response.result.error)}
}

Completionhandler (response)
})
}

public static Func Dictionarymapperserializer (), Responseserializer<anyobject, nserror> {
Return Responseserializer {request, response, data, error in
Guard Error = = Nil else {return. Failure (error!)}

If let response = response where Response.statuscode = = 204 {return. Success (NSNull ())}

Guard Let ValidData = data where validdata.length > 0 else {
Let reason = "JSON could isn't be serialized. Input data was nil or zero length. "
Let error = Errorhandler.error (Code:ErrorCode.SerializationFailed.rawValue, Reason:reason)
return. Failure (Error)
}

Let Json:anyobject?
do {
JSON = Try Nsjsonserialization.jsonobjectwithdata (data!, options:NSJSONReadingOptions.AllowFragments)
} catch {
return. Failure (Error as Nserror)
}

NSLog ("\n/*----Response----\nrequest URL = \ (Request?. urlstring) \n\nresult = \ (JSON) \ n------------------*/\n ")

Let code = JSON? [ResponseData.Code.rawValue] as? String
Guard Let _ = code else {
Let reason = "Data struct invalid."
Let error = Errorhandler.error (Code:ErrorCode.DataStructInvalid.rawValue, Reason:reason)
return. Failure (Error)
}

Guard code! = = ResponseData.Success.rawValue else {
Let reason = json? [ResponseData.Msg.rawValue] as? String
Let error = Errorhandler.error (Code:int (code!)!, Reason:reason)
return. Failure (Error)
}

Guard Let result = json? [ResponseData.Result.rawValue] Else {
return. Success (NSNull ())
}

return. Success (result!)
}
}} 5. Interface InvocationHud.show (. Labeledprogress (title: "", subtitle: "Login ..."))

Network.request (Method:Alamofire.Method.POST, Path:URLPath.Login, Parameters: ["Account": Account, "password": PASSWORDMD5])
. responseobject {(Response:alamofire.response<user, nserror>) in
If response.result.isSuccess {
Userhelp.sava (User:response.result.value!,password:password)

Hud.flash (. Success, Delay:0.0,completion: {finish in
Appdelegate.switchtomain ()
})
} else {
Hud.flash (. Labelederror (title: "", Subtitle:response.result.error?) localizeddescription), delay:0.5)
}}

Swift Project Setup

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.