胆固醇高是什么意思| 川崎病有什么症状| 甲亢吃什么药最有效| 土豆不能和什么食物一起吃| 口什么心什么| 天河水是什么意思| 夜盲症缺什么| 风生水起是什么意思| 肝内小囊肿是什么意思| 沉香木是什么| 乌江鱼是什么鱼| 派出所是干什么的| 报销凭证是什么| 交界性心律是什么意思| 红曲粉是什么东西| 子宫内膜增生有什么症状| l代表什么单位| 消化不良吃什么食物好| 鳏寡孤独是什么意思| 尿渗透压低是什么原因| 玛尼是什么意思| 龙须菜是什么| 叶酸片什么时候吃| lagogo是什么牌子| 十八岁属什么生肖| 白鸭是什么鸭| 12月26日什么星座| 左边头痛什么原因| 腋下有异味是什么原因| 执行标准是什么意思| 咳出血是什么原因| 左脚麻是什么原因| 美国为什么打伊拉克| 腿容易麻是什么原因| 40周年是什么婚| 鼻毛变白是什么原因| 冬至吃什么馅的饺子| 最近天气为什么这么热| 心脏不好喝什么茶比较好| 女累读什么| 打扰了是什么意思| chloe什么牌子| 雄黄是什么| 七六年属什么| 浅表性胃炎用什么药| 腰椎疼痛吃什么药| 胳膊肘发黑是什么原因| 饭后腹胀是什么原因| 氯化钠敷脸有什么作用| 文笔是什么意思| 七月一日是什么节日| 青蒿素是什么| 有氧运动和无氧运动有什么区别| 什么的鸭子| 酪氨酸酶是什么东西| 8月26日是什么星座| 红油是什么油| 检查血液挂什么科| 身上痒但是什么都没有| 道士是干什么的| 酊是什么意思| 快乐是什么意思| pm什么意思| 甲减是什么| 梦到钓鱼是什么征兆| 冒菜和麻辣烫有什么区别| 大专是什么意思| 后脖子出汗多是什么原因| 肠胃湿热吃什么药| 蚰蜒是什么| 左眼皮肿是什么原因引起的| 女生下面什么样| 米酒和黄酒有什么区别| 并发症是什么意思| 芸豆长什么样子| 私事是什么意思| 制片人是什么意思| 助产专业是干什么的| 电镀是做什么的| 甲醛中毒吃什么药解毒| 胆囊壁增厚是什么意思| 披什么散什么| 1977年什么命| 吃什么紧致皮肤抗衰老| 电影监制是做什么的| 今天什么日子老黄历| 大便干燥一粒一粒的吃什么药| gg是什么牌子的包包| 暧昧什么意思| hpv阳性有什么症状| 什么是职业道德| 乳房有溢液是什么原因| 胃息肉是什么原因造成的| 总胆红素升高是什么原因| 烊化兑服是什么意思| 熊猫尾巴什么颜色| 女性更年期潮热出汗吃什么药| cn什么意思| 肝不好挂什么科室| 胎动少是什么原因| 小资情调是什么意思| 沙拉酱是用什么做的| 去湿气喝什么茶| 节节草能治什么病| 为什么会缺钙| 血压高降不下来是什么原因| 艸是什么意思| 伤口止血用什么药| 1944年属什么生肖| 女人在什么时候最容易怀孕| 什么情况下做试管婴儿| 内消瘰疬丸主治什么病| 撸铁是什么意思| 来减一笔是什么字| 耳刀旁加步念什么| aj是什么鞋子| 肉炒什么菜谱大全| 牙齿矫正挂什么科| 西施长什么样| 高密度脂蛋白胆固醇低是什么意思| 地铁站务员是干什么的| 4.22是什么星座| 姜维属什么生肖| 幽门螺旋杆菌是什么病| 篦子是什么东西| 风热感冒咳嗽吃什么药| 梦见自己大肚子快生了是什么意思| 保守是什么意思| 结婚前要准备什么| 陈年是什么意思| 太监是什么意思| 踏空是什么意思| 胃胀胃疼吃什么药| 电压mv是什么意思| 扶摇是什么意思| 为什么做梦会说梦话| 隆科多为什么不姓佟| 理疗和按摩有什么区别| 葡萄糖氯化钠注射作用是什么| 低聚异麦芽糖是什么| 不解大便是什么原因| 什么肉好消化| 胃肠外科是看什么病的| 忌讳什么意思| 十月23日是什么星座| pp材质是什么| 降血压喝什么茶| 胆切除后吃什么好| 附耳是什么| 避孕药有什么副作用| 什么叫偶数| 艾灸痒痒的是什么原因| 男士适合戴什么手串| zn是什么元素| 甲减是什么| 子宫有积液是什么原因引起的| 女人漏尿是什么原因| 什么然而止| 麝香保心丸治什么病| 头七有什么规矩| 踩指压板有什么好处| 腐女是什么| 眼角有眼屎是什么原因| 考护士证需要什么条件| 软下疳是什么症状| 国民党为什么会失败| msv是什么单位| 舌头发白有齿痕是什么原因| 男人送女人项链代表什么| 什么床垫好| 家产是什么意思| 胃酸过多什么原因| 黑上衣配什么颜色裤子男| 微信被拉黑后显示什么| 黄体破裂吃什么药| 眼睛干痒滴什么眼药水| 贵州菜属于什么菜系| 淋巴结肿大挂什么科| 牙齿为什么会变黑| 问诊是什么意思| 杭州的市花是什么花| 什么是香港脚| vos是什么意思| 霉菌性阴道炎什么症状| 夫字五行属什么| 烂嘴角是什么原因| 吃完饭想吐是什么原因| 木石念什么| 钟鸣鼎食是什么意思| cbd是什么意思啊| 子宫肌瘤挂什么科室| 萧墙是什么意思| 梦到地震是什么意思| 拉肚子吃什么水果| 乌龟吃什么蔬菜| 羊水污染是什么原因造成的| 跟腱为什么会断裂| guess什么意思| 121什么意思| 城五行属什么| 查脂肪肝挂什么科室| 什么药补肾最好| 遁入空门是什么意思| 读书是为了什么| 尸臭是什么味道| 脑血栓前兆是什么症状表现| 蟋蟀吃什么食物| 虾仁和什么包饺子好吃| 什么样的雪花| 什么人容易得白肺病| 文科女生学什么专业好| 玫瑰花的花语是什么| 肌张力高有什么表现| 樱桃泡酒有什么功效| 吃什么对肺好| 糖类抗原50是什么指标| 三点水加个真念什么| 伏羲是什么意思| 黄体是什么| 锦衣卫是干什么的| 奀是什么意思| 长痔疮是什么引起的| 什么东西放进去是硬的拿出来是软的| 权衡利弊的意思是什么| 女人喝咖啡有什么好处和坏处| 查乳腺挂什么科| 中性粒细胞低吃什么药| 2009年是什么生肖年| 医者仁心是什么意思| 我的部首是什么| 为什么大便是绿色的| 彩虹像什么| 一把手是什么意思| 天蝎女喜欢什么样的男生| 多此一举是什么生肖| 鼻窦炎有什么特效药| 盘尼西林是什么药| 居酒屋是什么意思| 胃不消化吃什么药效果最好| 什么时期最容易怀孕| ntr是什么意思啊| 为什么做完爱下面会疼| 梦到和婆婆吵架是什么意思| 什么的高楼| 什么动物怕热| 银杏果长什么样| 梦见烙饼是什么意思| 念五行属什么| 为什么会子宫内膜增厚| 冠状沟溃疡是什么病| 腹腔淋巴结肿大是什么原因| 临床试验是什么意思| 什么是认知障碍| 三个土读什么| 师傅和师父有什么区别| 补维生素吃什么药最好| 脖子大是什么原因| 灰指甲挂号挂什么科| 皮肌炎是什么症状| 清明是什么意思| 孩子打喷嚏流鼻涕吃什么药| 什么肥什么壮| 面线是什么| 日有所思夜有所梦是什么意思| 百度

CocoaPods trunk is moving to be read-only. Read more on the blog, there are 17 months to go.

这些电影要是改编成VR游戏 那一定得吓到失眠

GCDWebServer 3.5.4

TestsTested ?
LangLanguage Obj-CObjective C
License NOASSERTION
ReleasedLast Release Mar 2020
百度 强化政治建设,增强机关党员干部“四个意识”旗帜鲜明讲政治是我们党作为马克思主义政党的根本要求。

Maintained by Pierre-Olivier Latour.



  • By
  • Pierre-Olivier Latour

Overview

Build Status Version Platform License

GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps. It was written from scratch with the following goals in mind:

  • Elegant and easy to use architecture with only 4 core classes: server, connection, request and response (see "Understanding GCDWebServer's Architecture" below)
  • Well designed API with fully documented headers for easy integration and customization
  • Entirely built with an event-driven design using Grand Central Dispatch for best performance and concurrency
  • No dependencies on third-party source code
  • Available under a friendly New BSD License

Extra built-in features:

  • Allow implementation of fully asynchronous handlers of incoming HTTP requests
  • Minimize memory usage with disk streaming of large HTTP request or response bodies
  • Parser for web forms submitted using "application/x-www-form-urlencoded" or "multipart/form-data" encodings (including file uploads)
  • JSON parsing and serialization for request and response HTTP bodies
  • Chunked transfer encoding for request and response HTTP bodies
  • HTTP compression with gzip for request and response HTTP bodies
  • HTTP range support for requests of local files
  • Basic and Digest Access authentications for password protection
  • Automatically handle transitions between foreground, background and suspended modes in iOS apps
  • Full support for both IPv4 and IPv6
  • NAT port mapping (IPv4 only)

Included extensions:

  • GCDWebUploader: subclass of GCDWebServer that implements an interface for uploading and downloading files using a web browser
  • GCDWebDAVServer: subclass of GCDWebServer that implements a class 1 WebDAV server (with partial class 2 support for macOS Finder)

What's not supported (but not really required from an embedded HTTP server):

  • Keep-alive connections
  • HTTPS

Requirements:

  • macOS 10.7 or later (x86_64)
  • iOS 8.0 or later (armv7, armv7s or arm64)
  • tvOS 9.0 or later (arm64)
  • ARC memory management only (if you need MRC support use GCDWebServer 3.1 or earlier)

Getting Started

Download or check out the latest release of GCDWebServer then add the entire "GCDWebServer" subfolder to your Xcode project. If you intend to use one of the extensions like GCDWebDAVServer or GCDWebUploader, add these subfolders as well. Finally link to libz (via Target > Build Phases > Link Binary With Libraries) and add $(SDKROOT)/usr/include/libxml2 to your header search paths (via Target > Build Settings > HEADER_SEARCH_PATHS).

Alternatively, you can install GCDWebServer using CocoaPods by simply adding this line to your Podfile:

pod "GCDWebServer", "~> 3.0"

If you want to use GCDWebUploader, use this line instead:

pod "GCDWebServer/WebUploader", "~> 3.0"

Or this line for GCDWebDAVServer:

pod "GCDWebServer/WebDAV", "~> 3.0"

And finally run $ pod install.

You can also use Carthage by adding this line to your Cartfile (3.2.5 is the first release with Carthage support):

github "swisspol/GCDWebServer" ~> 3.2.5

Then run $ carthage update and add the generated frameworks to your Xcode projects (see Carthage instructions).

Help & Support

For help with using GCDWebServer, it's best to ask your question on Stack Overflow with the gcdwebserver tag. For bug reports and enhancement requests you can use issues in this project.

Be sure to read this entire README first though!

Hello World

These code snippets show how to implement a custom HTTP server that runs on port 8080 and returns a "Hello World" HTML page to any request. Since GCDWebServer uses GCD blocks to handle requests, no subclassing or delegates are needed, which results in very clean code.

IMPORTANT: If not using CocoaPods, be sure to add the libz shared system library to the Xcode target for your app.

macOS version (command line tool):

#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"

int main(int argc, const char* argv[]) {
  @autoreleasepool {
    
    // Create server
    GCDWebServer* webServer = [[GCDWebServer alloc] init];
    
    // Add a handler to respond to GET requests on any URL
    [webServer addDefaultHandlerForMethod:@"GET"
                             requestClass:[GCDWebServerRequest class]
                             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
      
      return [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
      
    }];
    
    // Use convenience method that runs server on port 8080
    // until SIGINT (Ctrl-C in Terminal) or SIGTERM is received
    [webServer runWithPort:8080 bonjourName:nil];
    NSLog(@"Visit %@ in your web browser", webServer.serverURL);
    
  }
  return 0;
}

iOS version:

#import "GCDWebServer.h"
#import "GCDWebServerDataResponse.h"

@interface AppDelegate : NSObject <UIApplicationDelegate> {
  GCDWebServer* _webServer;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  
  // Create server
  _webServer = [[GCDWebServer alloc] init];
  
  // Add a handler to respond to GET requests on any URL
  [_webServer addDefaultHandlerForMethod:@"GET"
                            requestClass:[GCDWebServerRequest class]
                            processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
    
    return [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
    
  }];
  
  // Start server on port 8080
  [_webServer startWithPort:8080 bonjourName:nil];
  NSLog(@"Visit %@ in your web browser", _webServer.serverURL);
  
  return YES;
}

@end

macOS Swift version (command line tool):

webServer.swift

import Foundation
import GCDWebServer

func initWebServer() {

    let webServer = GCDWebServer()

    webServer.addDefaultHandler(forMethod: "GET", request: GCDWebServerRequest.self, processBlock: {request in
            return GCDWebServerDataResponse(html:"<html><body><p>Hello World</p></body></html>")
            
        })
        
    webServer.start(withPort: 8080, bonjourName: "GCD Web Server")
    
    print("Visit \(webServer.serverURL) in your web browser")
}

WebServer-Bridging-Header.h

#import <GCDWebServer/GCDWebServer.h>
#import <GCDWebServer/GCDWebServerDataResponse.h>

Web Based Uploads in iOS Apps

GCDWebUploader is a subclass of GCDWebServer that provides a ready-to-use HTML 5 file uploader & downloader. This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using a clean user interface in their web browser.

Simply instantiate and run a GCDWebUploader instance then visit http://{YOUR-IOS-DEVICE-IP-ADDRESS}/ from your web browser:

#import "GCDWebUploader.h"

@interface AppDelegate : NSObject <UIApplicationDelegate> {
  GCDWebUploader* _webUploader;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  _webUploader = [[GCDWebUploader alloc] initWithUploadDirectory:documentsPath];
  [_webUploader start];
  NSLog(@"Visit %@ in your web browser", _webUploader.serverURL);
  return YES;
}

@end

WebDAV Server in iOS Apps

GCDWebDAVServer is a subclass of GCDWebServer that provides a class 1 compliant WebDAV server. This lets users upload, download, delete files and create directories from a directory inside your iOS app's sandbox using any WebDAV client like Transmit (Mac), ForkLift (Mac) or CyberDuck (Mac / Windows).

GCDWebDAVServer should also work with the macOS Finder as it is partially class 2 compliant (but only when the client is the macOS WebDAV implementation).

Simply instantiate and run a GCDWebDAVServer instance then connect to http://{YOUR-IOS-DEVICE-IP-ADDRESS}/ using a WebDAV client:

#import "GCDWebDAVServer.h"

@interface AppDelegate : NSObject <UIApplicationDelegate> {
  GCDWebDAVServer* _davServer;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  _davServer = [[GCDWebDAVServer alloc] initWithUploadDirectory:documentsPath];
  [_davServer start];
  NSLog(@"Visit %@ in your WebDAV client", _davServer.serverURL);
  return YES;
}

@end

Serving a Static Website

GCDWebServer includes a built-in handler that can recursively serve a directory (it also lets you control how the "Cache-Control" header should be set):

macOS version (command line tool):

#import "GCDWebServer.h"

int main(int argc, const char* argv[]) {
  @autoreleasepool {
    
    GCDWebServer* webServer = [[GCDWebServer alloc] init];
    [webServer addGETHandlerForBasePath:@"/" directoryPath:NSHomeDirectory() indexFilename:nil cacheAge:3600 allowRangeRequests:YES];
    [webServer runWithPort:8080];
    
  }
  return 0;
}

Using GCDWebServer

You start by creating an instance of the GCDWebServer class. Note that you can have multiple web servers running in the same app as long as they listen on different ports.

Then you add one or more "handlers" to the server: each handler gets a chance to handle an incoming web request and provide a response. Handlers are called in a LIFO queue, so the latest added handler overrides any previously added ones.

Finally you start the server on a given port.

Understanding GCDWebServer's Architecture

GCDWebServer's architecture consists of only 4 core classes:

  • GCDWebServer manages the socket that listens for new HTTP connections and the list of handlers used by the server.
  • GCDWebServerConnection is instantiated by GCDWebServer to handle each new HTTP connection. Each instance stays alive until the connection is closed. You cannot use this class directly, but it is exposed so you can subclass it to override some hooks.
  • GCDWebServerRequest is created by the GCDWebServerConnection instance after HTTP headers have been received. It wraps the request and handles the HTTP body if any. GCDWebServer comes with several subclasses of GCDWebServerRequest to handle common cases like storing the body in memory or stream it to a file on disk.
  • GCDWebServerResponse is created by the request handler and wraps the response HTTP headers and optional body. GCDWebServer comes with several subclasses of GCDWebServerResponse to handle common cases like HTML text in memory or streaming a file from disk.

Implementing Handlers

GCDWebServer relies on "handlers" to process incoming web requests and generating responses. Handlers are implemented with GCD blocks which makes it very easy to provide your own. However, they are executed on arbitrary threads within GCD so special attention must be paid to thread-safety and re-entrancy.

Handlers require 2 GCD blocks:

  • The GCDWebServerMatchBlock is called on every handler added to the GCDWebServer instance whenever a web request has started (i.e. HTTP headers have been received). It is passed the basic info for the web request (HTTP method, URL, headers...) and must decide if it wants to handle it or not. If yes, it must return a new GCDWebServerRequest instance (see above) created with this info. Otherwise, it simply returns nil.
  • The GCDWebServerProcessBlock or GCDWebServerAsyncProcessBlock is called after the web request has been fully received and is passed the GCDWebServerRequest instance created at the previous step. It must return synchronously (if using GCDWebServerProcessBlock) or asynchronously (if using GCDWebServerAsyncProcessBlock) a GCDWebServerResponse instance (see above) or nil on error, which will result in a 500 HTTP status code returned to the client. It's however recommended to return an instance of GCDWebServerErrorResponse on error so more useful information can be returned to the client.

Note that most methods on GCDWebServer to add handlers only require the GCDWebServerProcessBlock or GCDWebServerAsyncProcessBlock as they already provide a built-in GCDWebServerMatchBlock e.g. to match a URL path with a Regex.

Asynchronous HTTP Responses

New in GCDWebServer 3.0 is the ability to process HTTP requests asynchronously i.e. add handlers to the server which generate their GCDWebServerResponse asynchronously. This is achieved by adding handlers that use a GCDWebServerAsyncProcessBlock instead of a GCDWebServerProcessBlock. Here's an example:

(Synchronous version) The handler blocks while generating the HTTP response:

[webServer addDefaultHandlerForMethod:@"GET"
                         requestClass:[GCDWebServerRequest class]
                         processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  
  GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
  return response;
  
}];

(Asynchronous version) The handler returns immediately and calls back GCDWebServer later with the generated HTTP response:

[webServer addDefaultHandlerForMethod:@"GET"
                         requestClass:[GCDWebServerRequest class]
                    asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {
  
  // Do some async operation like network access or file I/O (simulated here using dispatch_after())
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    GCDWebServerDataResponse* response = [GCDWebServerDataResponse responseWithHTML:@"<html><body><p>Hello World</p></body></html>"];
    completionBlock(response);
  });

}];

(Advanced asynchronous version) The handler returns immediately a streamed HTTP response which itself generates its contents asynchronously:

[webServer addDefaultHandlerForMethod:@"GET"
                         requestClass:[GCDWebServerRequest class]
                         processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  
  NSMutableArray* contents = [NSMutableArray arrayWithObjects:@"<html><body><p>\n", @"Hello World!\n", @"</p></body></html>\n", nil];  // Fake data source we are reading from
  GCDWebServerStreamedResponse* response = [GCDWebServerStreamedResponse responseWithContentType:@"text/html" asyncStreamBlock:^(GCDWebServerBodyReaderCompletionBlock completionBlock) {
    
    // Simulate a delay reading from the fake data source
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      NSString* string = contents.firstObject;
      if (string) {
        [contents removeObjectAtIndex:0];
        completionBlock([string dataUsingEncoding:NSUTF8StringEncoding], nil);  // Generate the 2nd part of the stream data
      } else {
        completionBlock([NSData data], nil);  // Must pass an empty NSData to signal the end of the stream
      }
    });
    
  }];
  return response;
  
}];

Note that you can even combine both the asynchronous and advanced asynchronous versions to return asynchronously an asynchronous HTTP response!

GCDWebServer & Background Mode for iOS Apps

When doing networking operations in iOS apps, you must handle carefully what happens when iOS puts the app in the background. Typically you must stop any network servers while the app is in the background and restart them when the app comes back to the foreground. This can become quite complex considering servers might have ongoing connections when they need to be stopped.

Fortunately, GCDWebServer does all of this automatically for you:

  • GCDWebServer begins a background task whenever the first HTTP connection is opened and ends it only when the last one is closed. This prevents iOS from suspending the app after it goes in the background, which would immediately kill HTTP connections to the client.
  • While the app is in the background, as long as new HTTP connections keep being initiated, the background task will continue to exist and iOS will not suspend the app for up to 10 minutes (unless under sudden and unexpected memory pressure).
  • If the app is still in the background when the last HTTP connection is closed, GCDWebServer will suspend itself and stop accepting new connections as if you had called -stop (this behavior can be disabled with the GCDWebServerOption_AutomaticallySuspendInBackground option).
  • If the app goes in the background while no HTTP connections are opened, GCDWebServer will immediately suspend itself and stop accepting new connections as if you had called -stop (this behavior can be disabled with the GCDWebServerOption_AutomaticallySuspendInBackground option).
  • If the app comes back to the foreground and GCDWebServer had been suspended, it will automatically resume itself and start accepting again new HTTP connections as if you had called -start.

HTTP connections are often initiated in batches (or bursts), for instance when loading a web page with multiple resources. This makes it difficult to accurately detect when the very last HTTP connection has been closed: it's possible 2 consecutive HTTP connections part of the same batch would be separated by a small delay instead of overlapping. It would be bad for the client if GCDWebServer suspended itself right in between. The GCDWebServerOption_ConnectedStateCoalescingInterval option solves this problem elegantly by forcing GCDWebServer to wait some extra delay before performing any action after the last HTTP connection has been closed, just in case a new HTTP connection is initiated within this delay.

Logging in GCDWebServer

Both for debugging and informational purpose, GCDWebServer logs messages extensively whenever something happens. Furthermore, when building GCDWebServer in "Debug" mode versus "Release" mode, it logs even more information but also performs a number of internal consistency checks. To enable this behavior, define the preprocessor constant DEBUG=1 when compiling GCDWebServer. In Xcode target settings, this can be done by adding DEBUG=1 to the build setting GCC_PREPROCESSOR_DEFINITIONS when building in "Debug" configuration. Finally, you can also control the logging verbosity at run time by calling +[GCDWebServer setLogLevel:].

By default, all messages logged by GCDWebServer are sent to its built-in logging facility, which simply outputs to stderr (assuming a terminal type device is connected). In order to better integrate with the rest of your app or because of the amount of information logged, you might want to use another logging facility.

GCDWebServer has automatic support for XLFacility (by the same author as GCDWebServer and also open-source): if it is in the same Xcode project, GCDWebServer should use it automatically instead of the built-in logging facility (see GCDWebServerPrivate.h for the implementation details).

It's also possible to use a custom logging facility - see GCDWebServer.h for more information.

Advanced Example 1: Implementing HTTP Redirects

Here's an example handler that redirects "/" to "/index.html" using the convenience method on GCDWebServerResponse (it sets the HTTP status code and "Location" header automatically):

[self addHandlerForMethod:@"GET"
                     path:@"/"
             requestClass:[GCDWebServerRequest class]
             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
    
  return [GCDWebServerResponse responseWithRedirect:[NSURL URLWithString:@"index.html" relativeToURL:request.URL]
                                          permanent:NO];
    
}];

Advanced Example 2: Implementing Forms

To implement an HTTP form, you need a pair of handlers:

  • The GET handler does not expect any body in the HTTP request and therefore uses the GCDWebServerRequest class. The handler generates a response containing a simple HTML form.
  • The POST handler expects the form values to be in the body of the HTTP request and percent-encoded. Fortunately, GCDWebServer provides the request class GCDWebServerURLEncodedFormRequest which can automatically parse such bodies. The handler simply echoes back the value from the user submitted form.
[webServer addHandlerForMethod:@"GET"
                          path:@"/"
                  requestClass:[GCDWebServerRequest class]
                  processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  
  NSString* html = @" \
    <html><body> \
      <form name=\"input\" action=\"/\" method=\"post\" enctype=\"application/x-www-form-urlencoded\"> \
      Value: <input type=\"text\" name=\"value\"> \
      <input type=\"submit\" value=\"Submit\"> \
      </form> \
    </body></html> \
  ";
  return [GCDWebServerDataResponse responseWithHTML:html];
  
}];

[webServer addHandlerForMethod:@"POST"
                          path:@"/"
                  requestClass:[GCDWebServerURLEncodedFormRequest class]
                  processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
  
  NSString* value = [[(GCDWebServerURLEncodedFormRequest*)request arguments] objectForKey:@"value"];
  NSString* html = [NSString stringWithFormat:@"<html><body><p>%@</p></body></html>", value];
  return [GCDWebServerDataResponse responseWithHTML:html];
  
}];

Advanced Example 3: Serving a Dynamic Website

GCDWebServer provides an extension to the GCDWebServerDataResponse class that can return HTML content generated from a template and a set of variables (using the format %variable%). It is a very basic template system and is really intended as a starting point to building more advanced template systems by subclassing GCDWebServerResponse.

Assuming you have a website directory in your app containing HTML template files along with the corresponding CSS, scripts and images, it's pretty easy to turn it into a dynamic website:

// Get the path to the website directory
NSString* websitePath = [[NSBundle mainBundle] pathForResource:@"Website" ofType:nil];

// Add a default handler to serve static files (i.e. anything other than HTML files)
[self addGETHandlerForBasePath:@"/" directoryPath:websitePath indexFilename:nil cacheAge:3600 allowRangeRequests:YES];

// Add an override handler for all requests to "*.html" URLs to do the special HTML templatization
[self addHandlerForMethod:@"GET"
                pathRegex:@"/.*\.html"
             requestClass:[GCDWebServerRequest class]
             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
    
    NSDictionary* variables = [NSDictionary dictionaryWithObjectsAndKeys:@"value", @"variable", nil];
    return [GCDWebServerDataResponse responseWithHTMLTemplate:[websitePath stringByAppendingPathComponent:request.path]
                                                    variables:variables];
    
}];

// Add an override handler to redirect "/" URL to "/index.html"
[self addHandlerForMethod:@"GET"
                     path:@"/"
             requestClass:[GCDWebServerRequest class]
             processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {
    
    return [GCDWebServerResponse responseWithRedirect:[NSURL URLWithString:@"index.html" relativeToURL:request.URL]
                                            permanent:NO];
    
];

Final Example: File Downloads and Uploads From iOS App

GCDWebServer was originally written for the ComicFlow comic reader app for iPad. It allow users to connect to their iPad with their web browser over WiFi and then upload, download and organize comic files inside the app.

ComicFlow is entirely open-source and you can see how it uses GCDWebServer in the WebServer.h and WebServer.m files.

腮腺炎的症状是什么 数字化摄影dr是检查什么 应景是什么意思 高血脂看什么科 深入交流是什么意思
什么水是碱性水 梦见骨灰盒是什么征兆 韩红是什么民族 羽立念什么 割包为什么很多人后悔
约稿是什么意思 什么思而行 央行行长什么级别 举的部首是什么 锖色是什么颜色
club monaco是什么牌子 洗纹身去医院挂什么科 白羊男和什么星座最配 吃什么能帮助睡眠 紫藤花什么时候开花
桂林山水甲天下是什么意思hcv8jop4ns7r.cn 咽喉炎吃什么消炎药hcv9jop4ns5r.cn 俏皮话是什么意思hcv9jop2ns3r.cn 二月初五是什么星座hcv9jop4ns8r.cn 滥竽充数的充是什么意思hcv8jop4ns4r.cn
小样什么意思hcv9jop0ns1r.cn 缺钾会出现什么症状onlinewuye.com 金益什么字hcv8jop3ns3r.cn 阳虚是什么原因引起的hcv8jop1ns3r.cn 手机贴什么膜最好hcv9jop4ns8r.cn
肝钙化斑是什么意思hcv8jop4ns8r.cn 来大姨妈能吃什么水果baiqunet.com 喝红糖水有什么好处hcv8jop5ns0r.cn 什么叫意象hcv8jop7ns8r.cn 流清鼻涕吃什么药好hcv9jop2ns5r.cn
樊胜美是什么电视剧hcv9jop8ns3r.cn 经常喝柠檬水有什么好处和坏处520myf.com 孕妇梦见老公出轨是什么意思hcv9jop3ns8r.cn 一个车一个罔是什么字hcv7jop6ns0r.cn 健脾胃吃什么hcv8jop6ns4r.cn
百度