1. 先用Pods 把第三方原件 加入進來
platform :ios, '5.0'
pod 'AFNetworking', '~> 1.2'
2.
將AFNetworking 加入參考
#import <AFNetworking.h>
可以到Xcode資料夾底下 Supporting Files
的 .pch 檔案的裡面
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <AFNetworking.h>
#endif
3.
簡單範例
static NSString *const BaseURLString = @"http://140.131.95.60/TESTAPI/";
NSString *weatherUrl = [NSString stringWithFormat:@"%@api/product", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// self.weather = (NSDictionary *)JSON;
// self.title = @"JSON Retrieved";
// [self.tableView reloadData];
NSLog(@"%@",response);
NSLog(@"%@",JSON);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[NSString stringWithFormat:@"%@",error]delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];
[operation start];
4.接下來要解出json的封包
NSDictionary *JSONdata = (NSDictionary *)JSON;
for (NSDictionary *carDict in JSONdata) {
NSString * email = [carDict valueForKey:@"email"];
NSLog(@"%@",email);
}
傳回
2013-07-11 17:43:54.981 testcocoapods[15122:a0b] john6812711@gmail.com
2013-07-11 17:43:54.983 testcocoapods[15122:a0b] john6812711@gmail.com
2013-07-11 17:43:54.984 testcocoapods[15122:a0b] john6812711@gmail.com
2013-07-11 17:43:54.984 testcocoapods[15122:a0b] john6812711@gmail.com
2013-07-11 17:43:54.984 testcocoapods[15122:a0b] john@yahoo
2013-07-11 17:43:54.984 testcocoapods[15122:a0b] iLoveJohn@gmail.com
2013-07-11 17:43:54.985 testcocoapods[15122:a0b] john6812711@gmail.com
2013-07-11 17:43:54.985 testcocoapods[15122:a0b] john6812711@yahoo.com.tw
2013-07-11 17:43:54.986 testcocoapods[15122:a0b] john6812711@gmail.com
0 意見:
張貼留言