League2eb

可以拿來幹嘛?

可以將您想要紀錄的字串、資訊自動填寫到自己建立的Google表單(例如偷偷記錄使用者的帳 號密碼之類??????)講直白一點就是「利用Google表單建立微型資料庫」

首先創建一個空白的表單

輸入完表單標題後下方的問題欄位狀型態改為「段落」

點選右上角的齒輪

把「需要登入」的選項全部取消後儲存

把表單的網址中複製下來「暫時放到記事本」並且把網址最後面的「edit」刪除

點選右上角「…」再點選「取得預先填入的連結」

隨便輸入一個回答,輸入完畢後點選提交

會看到上方出現一串網址,複製到剪貼簿後會看到其中「entry.201377372」,這是欄位名稱(如果表單中有多個回答就會有多個此欄位,後面會在程式碼中提到,所以這邊就先記著)

欄位像這樣子

9.把剛剛複製的網址貼到瀏覽器並且按下Enter
再次點選提交,提交並跳轉後把網址後面的「formResponse」複製起來貼到第5步原本刪除的「edit」位置

所以你的請求網址會像這樣子
1
https://docs.google.com/forms/d/1TEIA3i4C0uY6Ha3bhM5SkFzCLO61TvLzbxw-2CKDR5Y/formResponse

在專案中新增一個類別叫「GoogleFormRequest」,不囉唆直上代碼

GoogleFormRequest.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import <Foundation/Foundation.h>

@protocol GoogleFormDelegate <NSObject>

@optional

- (void)didPOSTRequestSuccess;

@end

@interface GoogleFormRequest : NSObject
@property (nonatomic, strong) id<GoogleFormDelegate> delegate;
+ (instancetype)sharedInstance;
- (void)postWithSomething:(NSString *)something;
@end

GoogleFormRequest.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#import "GoogleFormRequest.h"

static GoogleFormRequest *singletonGoogleFormRequest = nil;

@implementation GoogleFormRequest

+ (instancetype)sharedInstance {
if (singletonGoogleFormRequest == nil) {
singletonGoogleFormRequest = [GoogleFormRequest new];
}
return singletonGoogleFormRequest;
}


- (void)postWithSomething:(NSString *)something {
//初始化請求
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:你的請求地址]];
/*默認的請求為GET,這邊手動設定為POST
但其實在Google表單的請求中有發現,Google有開GET與POST的API,所以這兩種都可以使用
*/
[urlRequest setHTTPMethod:@"POST"];
/*設定參數並轉換為Data 允許特殊字符(這邊專門做給輸入中文時使用,英文沒有這困擾) */
NSData *parameterToData = [[[NSString stringWithFormat:@"你的參數名稱=%@",something] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] dataUsingEncoding:NSUTF8StringEncoding];
//再把資料放到這段請求的Body中
[urlRequest setHTTPBody:parameterToData];
//請求開始
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//宣告網路回應
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
//訪問允許判斷
if(httpResponse.statusCode == 200) {
//看你要幹什麼?
[self.delegate didPOSTRequestSuccess];
}
}];
[dataTask resume];
}
@end

ViewController.m 實作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "ViewController.h"
#import "GoogleFormRequest.h"
@interface ViewController () <GoogleFormDelegate> {
dispatch_queue_t queueSerial;
}
@property (nonatomic, strong) GoogleFormRequest *comm;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
queueSerial = dispatch_queue_create("comm.queue.serial", nil);
self.comm = [GoogleFormRequest sharedInstance];
self.comm.delegate = self;

dispatch_async(queueSerial, ^{
[_comm postWithDevice:@"測試" WithDate:nil];
});
}

- (void)didPOSTRequestSuccess {
NSLog(@"請求成功");
}

 評論