日本搞逼视频_黄色一级片免费在线观看_色99久久_性明星video另类hd_欧美77_综合在线视频

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > php開源 > 綜合技術 > iOS網絡編程

iOS網絡編程

來源:程序員人生   發布時間:2015-03-31 08:34:24 閱讀次數:2547次

         ios網絡編程(http、socket)

分類: OS-X/iOS開發 7369人瀏覽 評論(3) 收藏 舉報

目錄(?)[+]

http編程綜述:亦可稱為soap編程。通常情況下,http編程要比socket編程相對要簡單易用很多。所以用的最廣廣泛。

1、http編程其實就是http要求。http要求最長用的方法是 get 和 post 方法。
==》get方法和post方法相比理解起來比較簡單,get方法可以直接要求1個url,也能夠url后面拼接上參數作為1個新的url地址進行要求。get方法后面的value要經過unicode編碼。form的enctype屬性默許為application/x-www-form-urlencoded。不能發送2進制文件。
==》post方法相對要復雜1些。首先post方法要設置key和value ,所有的key和value都會拼接成 key1=value1&key2=value2的樣式的字符串,然后這個字符串轉化為2進制放到 http要求的body中。當要求發送的時候,也就跟隨body1起傳給服務器。http要求Content-Type設置為:application/x-www-form-urlencoded。這里講的只是簡單的post要求,1般發送文件不會選擇這類方式(從技術方面斟酌也能夠發送文件,就是把文件以 key 和 value的方式放入)。下面我們再討論1下post發送2進制文件更加普遍的方法。

2、HTTP協議是甚么?
簡單來講,就是1個基于利用層的通訊規范:雙方要進行通訊,大家都要遵照1個規范,這個規范就是HTTP協議。
HTTP協議能做甚么?
很多人首先1定會想到:閱讀網頁。沒錯,閱讀網頁是HTTP的主要利用,但是這其實不代表HTTP就只能利用于網頁的閱讀。HTTP是1種協議,只要通訊的雙方都遵照這個協議,HTTP就可以有用武之地。比如我們經常使用的QQ,迅雷這些軟件,都會使用HTTP協議(還包括其他的協議)。
HTTP協議如何工作?
大家都知道1般的通訊流程:首先客戶端發送1個要求(request)給服務器服務器在接收到這個要求后將生成1個響應(response)返回給客戶端。
在這個通訊的進程中HTTP協議在以下4個方面做了規定:
1.         Request和Response的格式()
2.         建立連接的方式(1、非持久連接 2、持久連接)
3.         緩存的機制
4.         響應授權激起機制
(利用場合)
5.        基于HTTP的利用(1、 HTTP代理 2、多線程下載 3、 HTTPS傳輸協議原理 4、開發web程序經常用的Request Methods 5、用戶與服務器的交互)


經常使用cocoa內部類: 
1,Reachability.h 蘋果demo支持網絡連接診斷
2,NSConnection連接、NSMutableURLRequest URL網址的要求封裝包
3,NSXMLParser XML解析

經常使用第3方庫:
1,ASIHttprequest 庫

操作步驟:
1:檢查網絡環境(3G/WIFI)
2:發起NSConnection要求
3:處理返回xml數據包(NSXMLParser解析xml文件),或返回文件png、pdf之類
4:若返回數據包中含有待下載的圖片下載地址。則重復2、3步驟下載下來圖片。只不過3中返回的是文件。

socket編程綜述:
經常使用cocoa內部類:
經常使用第3方庫:1,Asyncsocket庫
操作步驟:



http網絡編程實例   

1:確認網絡環境3G/WIFI 
 
    1. 添加源文件和framework 
     
    開發Web等網絡利用程序的時候,需要確認網絡環境,連接情況等信息。如果沒有處理它們,是不會通過Apple的審查的。 
    Apple 的 例程 Reachability 中介紹了獲得/檢測網絡狀態的方法。要在利用程序程序中使用Reachability,首先要完成以下兩部: 
     
    1.1. 添加源文件: 
    在你的程序中使用 Reachability 只須將該例程中的 Reachability.h 和 Reachability.m 拷貝到你的工程中。以下圖: 
 
     
     
    1.2.添加framework: 
    將SystemConfiguration.framework 添加進工程。以下圖: 
     
     
    2. 網絡狀態 
     
    Reachability.h中定義了3種網絡狀態: 
    typedef enum { 
        NotReachable = 0,            //無連接 
        ReachableViaWiFi,            //使用3G/GPRS網絡 
        ReachableViaWWAN            //使用WiFi網絡 
    } NetworkStatus; 
     
    因此可以這樣檢查網絡狀態: 
 
    Reachability *r = [Reachability reachabilityWithHostName:@“www.apple.com”]; 
    switch ([r currentReachabilityStatus]) { 
            case NotReachable: 
                    // 沒有網絡連接 
                    break; 
            case ReachableViaWWAN: 
                    // 使用3G網絡 
                    break; 
            case ReachableViaWiFi: 
                    // 使用WiFi網絡 
                    break; 
    } 
     
    3.檢查當前網絡環境 
    程序啟動時,如果想檢測可用的網絡環境,可以像這樣 
    // 是不是wifi 
    + (BOOL) IsEnableWIFI { 
        return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); 
    } 
 
    // 是不是3G 
    + (BOOL) IsEnable3G { 
        return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); 
    } 
    例子: 
    - (void)viewWillAppear:(BOOL)animated {     
    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus == NotReachable) &&  
            ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) { 
            self.navigationItem.hidesBackButton = YES; 
            [self.navigationItem setLeftBarButtonItem:nil animated:NO]; 
        } 
    } 
 
    4. 鏈接狀態的實時通知 
    網絡連接狀態的實時檢查,通知在網絡利用中也是10分必要的。接續狀態產生變化時,需要及時地通知用戶: 
     
    Reachability 1.5版本 
    // My.AppDelegate.h 
    #import "Reachability.h" 
 
    @interface MyAppDelegate : NSObject <UIApplicationDelegate> { 
        NetworkStatus remoteHostStatus; 
    } 
 
    @property NetworkStatus remoteHostStatus; 
 
    @end 
 
    // My.AppDelegate.m 
    #import "MyAppDelegate.h" 
 
    @implementation MyAppDelegate 
    @synthesize remoteHostStatus; 
 
    // 更新網絡狀態 
    - (void)updateStatus { 
        self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus]; 
    } 
 
    // 通知網絡狀態 
    - (void)reachabilityChanged:(NSNotification *)note { 
        [self updateStatus]; 
        if (self.remoteHostStatus == NotReachable) { 
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"AppName", nil) 
                         message:NSLocalizedString (@"NotReachable", nil) 
                        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
            [alert show]; 
            [alert release]; 
        } 
    } 
 
    // 程序啟動器,啟動網絡監視 
    - (void)applicationDidFinishLaunching:(UIApplication *)application { 
     
        // 設置網絡檢測的站點 
        [[Reachability sharedReachability] setHostName:@"www.apple.com"]; 
        [[Reachability sharedReachability] setNetworkStatusNotificati*****Enabled:YES]; 
        // 設置網絡狀態變化時的通知函數 
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) 
                                                 name:@"kNetworkReachabilityChangedNotification" object:nil]; 
        [self updateStatus]; 
    } 
 
    - (void)dealloc { 
        // 刪除通知對象 
        [[NSNotificationCenter defaultCenter] removeObserver:self]; 
        [window release]; 
        [super dealloc]; 
    }  
     
    Reachability 2.0版本 
     
 
    // MyAppDelegate.h 
    @class Reachability; 
 
        @interface MyAppDelegate : NSObject <UIApplicationDelegate> { 
            Reachability  *hostReach; 
        } 
 
    @end 
 
    // MyAppDelegate.m 
    - (void)reachabilityChanged:(NSNotification *)note { 
        Reachability* curReach = [note object]; 
        NSParameterAssert([curReach isKindOfClass: [Reachability class]]); 
        NetworkStatus status = [curReach currentReachabilityStatus]; 
     
        if (status == NotReachable) { 
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AppName"" 
                              message:@"NotReachable" 
                              delegate:nil 
                              cancelButtonTitle:@"YES" otherButtonTitles:nil]; 
                              [alert show]; 
                              [alert release]; 
        } 
    } 
                               
    - (void)applicationDidFinishLaunching:(UIApplication *)application { 
        // ... 
                   
        // 監測網絡情況 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                              selector:@selector(reachabilityChanged:) 
                              name: kReachabilityChangedNotification 
                              object: nil]; 
        hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain]; 
        hostReach startNotifer]; 
        // ... 
    } 
 
 
2:使用NSConnection下載數據 
     
    1.創建NSConnection對象,設置拜托對象 
     
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; 
    [NSURLConnection connectionWithRequest:request delegate:self]; 
     
    2. NSURLConnection delegate拜托方法 
        - (void)connection:(NSURLConnection *)connection didReceiveResp*****e:(NSURLResp*****e *)resp*****e;   
        - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;   
        - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;   
        - (void)connectionDidFinishLoading:(NSURLConnection *)connection;   
 
    3. 實現拜托方法 
    - (void)connection:(NSURLConnection *)connection didReceiveResp*****e:(NSURLResp*****e *)resp*****e { 
        // store data 
        [self.receivedData setLength:0];            //通常在這里先清空接受數據的緩存 
    } 
     
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
           /* appends the new data to the received data */ 
        [self.receivedData appendData:data];        //可能屢次收到數據,把新的數據添加在現有數據最后 
    } 
 
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
        // 毛病處理 
    } 
 
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
        // disconnect 
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;    
        NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; 
        NSLog(returnString); 
        [self urlLoaded:[self urlString] data:self.receivedData]; 
        firstTimeDownloaded = YES; 
    } 
 
3:使用NSXMLParser解析xml文件 
 
    1. 設置拜托對象,開始解析 
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或也能夠使用initWithContentsOfURL直接下載文件,但是有1個緣由不這么做: 
    // It's also possible to have NSXMLParser download the data, by passing it a URL, but this is not desirable 
    // because it gives less control over the network, particularly in responding to connection errors. 
    [parser setDelegate:self]; 
    [parser parse]; 
 
    2. 經常使用的拜托方法 
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName  
                                namespaceURI:(NSString *)namespaceURI 
                                qualifiedName:(NSString *)qName  
                                attributes:(NSDictionary *)attributeDict; 
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName  
                                namespaceURI:(NSString *)namespaceURI  
                                qualifiedName:(NSString *)qName; 
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; 
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError; 
 
    static NSString *feedURLString = @"http://www.yifeiyang.net/test/test.xml"; 
 
    3.  利用舉例 
    - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error 
    { 
        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL]; 
        [parser setDelegate:self]; 
        [parser setShouldProcessNamespaces:NO]; 
        [parser setShouldReportNamespacePrefixes:NO]; 
        [parser setShouldResolveExternalEntities:NO]; 
        [parser parse]; 
        NSError *parseError = [parser parserError]; 
        if (parseError && error) { 
            *error = parseError; 
        } 
        [parser release]; 
    } 
 
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI  
                                        qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{ 
        // 元素開始句柄 
        if (qName) { 
            elementName = qName; 
        } 
        if ([elementName isEqualToString:@"user"]) { 
            // 輸出屬性值 
            NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]); 
        } 
    } 
 
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI  
                                        qualifiedName:(NSString *)qName 
    { 
        // 元素終了句柄 
        if (qName) { 
               elementName = qName; 
        } 
    } 
 
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
    { 
        // 獲得元素的text 
    } 
 
    NSError *parseError = nil; 
    [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString] parseError:&parseError]; 

//實例
//
//  NLViewController.m
//  NetWorkTest
//
//  Created by Nono on 12⑸⑴6.
//  Copyright (c) 2012年 NonoWithLilith. All rights reserved.
//
#import "NLViewController.h"

@interface NLViewController ()

@end

@implementation NLViewController
@synthesize label = _label;
@synthesize data = _data;
@synthesize connection = _connection;
- (void)dealloc{
    [self.label release];
    [self.data release];
    [super dealloc];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 400)];
    self.label = label;
    label.textAlignment = UITextAlignmentCenter;
    [label setNumberOfLines:0];
    label.lineBreakMode = UILineBreakModeWordWrap; 
    self.label.text = @"正在在要求數據";
    [self.view addSubview:label];
    [label release];
    //step 1:要求地址
    NSString *urlString = @"http://www.google.com";
    NSURL *url = [NSURL URLWithString:urlString];
    //step 2:實例化1個request
    NSURLRequest *requrst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    //step 3:創建鏈接
    self.connection = [[NSURLConnection alloc] initWithRequest:requrst delegate:self];
    if ( self.connection) {
        NSLog(@"鏈接成功");
    }else {
        NSLog(@"鏈接失敗");
    }
    
    [url release];
    [urlString release];
    [requrst release];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    self.label = nil;
    self.data = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark-
#pragma NSUrlConnectionDelegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //接受1個服務端回話,再次1般初始化接受數據的對象
   
    NSLog(@"返回數據類型:%@",[response textEncodingName]); 
    NSMutableData *d = [[NSMutableData alloc] init];
     self.data = d;
    [d release];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //接受返回數據,這個方法可能會被調用屢次,因此將屢次返回數據加起來
    
    NSUInteger datalength = [data length];
    NSLog(@"返回數據量:%d",datalength);
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //連接結束
    
    NSLog(@"%d:",[self.data length]);
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *mystr = [[NSString alloc] initWithData:_data encoding:enc];
   // string i
    NSLog(@"最后的結果:%@",mystr);
    self.label.text = mystr;
    [mystr release];
    [self.connection release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //鏈接毛病
}

@end
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 黄色av免费在线 | 久久精品无码一区二区三区 | 国产精品一国产精品 | 直接看的av网站 | 成人高清 | 直接看av的网站 | caoprom超碰| 国内精品在线播放 | 久久国产精品免费一区二区三区 | 欧美片子 | 欧美日韩三区 | 99视频在线播放 | 国产成人精品久久二区二区91 | 亚洲福利 | 天堂中文资源在线 | 99久久婷婷国产综合精品免费 | 欧美精选一区 | 欧美夜夜 | 精品国产免费久久久久久尖叫 | 亚洲高清中文字幕 | 偷拍自拍在线观看 | 国产免费视频在线 | 欧美亚一区二区 | 亚洲精彩免费视频 | 91午夜精品 | 污网站免费看 | 精品国产一区二区三区在线观看 | 国产二区三区 | 日韩精品久久久久久 | 欧美成人免费在线视频 | 午夜成人在线视频 | 久久久久成人网 | 国产a视频 | 麻豆二区 | 亚洲精品一区 | 亚洲六月丁香色婷婷综合久久 | 欧美一区二区大片 | 伊人成人在线视频 | 久久av一区二区三区 | 国产啪视频 | 福利视频一区二区三区 |